Use javascript in html attribute

How to add/update an attribute to an HTML element using JavaScript?

I’m trying to find a way that will add / update attribute using JavaScript. I know I can do it with setAttribute() function but that doesn’t work in IE.

4 Answers 4

You can read here about the behaviour of attributes in many different browsers, including IE.

element.setAttribute() should do the trick, even in IE. Did you try it? If it doesn’t work, then maybe element.attributeName = ‘value’ might work.

this works. it creates attribute if it doesn’t exists and updates it if it does exist. is this documented somewhere as far as how this works?

When I do the following: document.getElementById(«nav»).setAttribute(«class», «active»); it works in the Chrome JS console, but in the actual page it doesn’t work..any ideas? By the way, in the actual page I include the .js file before the end of the body scope.

What seems easy is actually tricky if you want to be completely compatible.

var e = document.createElement('div');

Let’s say you have an id of ‘div1’ to add.

e['id'] = 'div1'; e.id = 'div1'; e.attributes['id'] = 'div1'; e.createAttribute('id','div1')

These will all work except the last in IE 5.5 (which is ancient history at this point but still is XP’s default with no updates).

But there are contingencies, of course. Will not work in IE prior to 8: e.attributes[‘style’] Will not error but won’t actually set the class, it must be className: e[‘class’] .
However, if you’re using attributes then this WILL work: e.attributes[‘class’]

In summary, think of attributes as literal and object-oriented.

In literal, you just want it to spit out x=’y’ and not think about it. This is what attributes, setAttribute, createAttribute is for (except for IE’s style exception). But because these are really objects things can get confused.

Since you are going to the trouble of properly creating a DOM element instead of jQuery innerHTML slop, I would treat it like one and stick with the e.className = ‘fooClass’ and e.id = ‘fooID’. This is a design preference, but in this instance trying to treat is as anything other than an object works against you.

It will never backfire on you like the other methods might, just be aware of class being className and style being an object so it’s style.width not style=»width:50px». Also remember tagName but this is already set by createElement so you shouldn’t need to worry about it.

This was longer than I wanted, but CSS manipulation in JS is tricky business.

Источник

Can you set a javascript function name as an html attribute?

Is it possible to write an html attribute that will store the name of a javascript function and then extract that val() and execute that function? Example:

fn = $('#example').data('function-name'); fn; 

That may help you : stackoverflow.com/a/26020014/2324107. It is used for variable, but it is the same way with functions.

3 Answers 3

You can, yes. Whether you should is another question entirely, to which the answer is almost certainly «no» (in terms of executing the string; in terms of the alternative shown below, there are times it’s useful).

The way you’d evaluate that snippet of code (what you have isn’t just a function name, because of the () ) would be to use the dreaded eval :

There’s almost always a better option than using eval . (See below.)

$("#example").on("click", function() < var fn = $("#example").attr("data-function-name"); eval(fn); >); function showAllElements()

One of the better options is to store your function references as properties on an object, and then use brackets notation to get the function reference based on the function name:

var functions = < showAllElements: function() < alert("showAllElements was called"); >>; $("#example").on("click", function() < var fn = $("#example").attr("data-function-name"); functions[fn](); >);

Note that there, I’m just storing the function name, not arbitrary code.

Update: See canon’s answer for a clever way to handle it if you have your functions nested inside an object, e.g. mumble.foo.doSomething , using reduce . ( reduce is an ES5 feature, but it’s polyfillable.)

Side note: Unless you’re doing something more than just retrieving the value of a data-* attribute, don’t use data , use attr . data initializes a data cache for the element, reads in all of the data-* attributes for that element, and copies them to cache. If you’re not using it, there’s no reason to do that. The idea that you use data to access data-* attributes is a common misconception.

Источник

Подключение JavaScript к HTML

Осваивайте профессию, начните зарабатывать, а платите через год!

Курсы Python Ак­ция! Бес­плат­но!

Станьте хакером на Python за 3 дня

Веб-вёрстка. CSS, HTML и JavaScript

Станьте веб-разработчиком с нуля

В этой главе мы займемся размещением сценариев в HTML-документе, чтобы иметь возможность использовать их для оперативной модификации HTML-документа. Для вставки JavaScript-кoдa в НТМL-страницу обычно используют элемент .

Первая программа

Чтобы ваша первая пpoгpaммa (или сценарий) JavaScript запустилась, ее нужно внедрить в НТМL-документ.
Сценарии внедряются в HTML-документ различными стандартными способами:

  • поместить код непосредственно в атрибут события HTML-элемента;
  • поместить код между открывающим и закрывающим тегами ;
  • поместить все ваши скрипты во внешний файл (с расширением .js), а затем связать его с документом HTML.

JavaScript в элементе script

Самый простой способ внедрения JavaScript в HTML-документ – использование тега . Теги часто помещают в элемент , и ранее этот способ считался чуть ли не обязательным. Однако в наши дни теги используются как в элементе , так и в теле веб-страниц.

Таким образом, на одной веб-странице могут располагаться сразу несколько сценариев. В какой последовательности браузер будет выполнять эти сценарии? Как правило, выполнение сценариев браузерами происходит по мере их загрузки. Браузер читает HTML-документ сверху вниз и, когда он встречает тег , рассматривает текст программы как сценарий и выполняет его. Остальной контент страницы не загружается и не отображается, пока не будет выполнен весь код в элементе .

Обратите внимание: мы указали атрибут language тега , указывающий язык программирования, на котором написан сценарий. Значение атрибута language по умолчанию – JavaScript, поэтому, если вы используете скрипты на языке JavaScript, то вы можете не указывать атрибут language .

JavaScript в атрибутах событий HTML-элементов

Вышеприведенный сценарий был выполнен при открытии страницы и вывел строку: «Привет, мир!». Однако не всегда нужно, чтобы выполнение сценария начиналось сразу при открытии страницы. Чаще всего требуется, чтобы программа запускалась при определенном событии, например при нажатии какой-то кнопки.

В следующем примере функция JavaScript помещается в раздел HTML-документа. Вот пример HTML-элемента с атрибутом события, обеспечивающим реакцию на щелчки мышью. При нажатии кнопки генерируется событие onclick.

Внешний JavaScript

Если JavaScript-кода много – его выносят в отдельный файл, который, как правило, имеет расширение .js .

Чтобы включить в HTML-документ JavaScript-кoд из внешнего файла, нужно использовать атрибут src (source) тега . Его значением должен быть URL-aдpec файла, в котором содержится JS-код:

В этом примере указан абсолютный путь к файлу с именем script.js, содержащему скрипт (из корня сайта). Сам файл должен содержать только JavaScript-кoд, который иначе располагался бы между тегами .

По аналогии с элементом атрибуту src элемента можно назначить полный URL-aдpec, не относящийся к домену текущей НТМL-страницы:

На заметку: Подробнее о путях файлов читайте в разделе «Абсолютные и относительные ссылки».

Чтобы подключить несколько скриптов, используйте несколько тегов:

Примечание: Элемент , хотя внешний сценарий выполняется, встроенный код игнорируется.

Независимо от того, как JS-код включается в НТМL-документ, элементы интерпретируются браузером в том порядке, в котором они расположены в HTML-документе. Сначала интерпретируется код первого элемента , затем браузер приступает ко второму элементу и т. д.

Внешние скрипты практичны, когда один и тот же код используется во многих разных веб-страницах. Браузер скачает js-файл один раз и в дальнейшем будет брать его из своего кеша, благодаря чему один и тот же скрипт, содержащий, к примеру, библиотеку функций, может использоваться на разных страницах без полной перезагрузки с сервера. Кроме этого, благодаря внешним скриптам, упрощается сопровождение кода, поскольку вносить изменения или исправлять ошибки приходится только в одном месте.

Примечание: Во внешние файлы копируется только JavaScript-код без указания открывающего и закрывающего тегов .

Расположение тегов

Вы уже знаете, что браузер читает HTML-документ сверху вниз и, начинает отображать страницу, показывая часть документа до тега . Встретив тег , переключается в JavaScript-режим и выполняет сценарий. Закончив выполнение, возвращается обратно в HTML-режим и отображает оставшуюся часть документа.

Это наглядно демонстрирует следующий пример. Метод alert() выводит на экран модальное окно с сообщением и приостанавливает выполнение скрипта, пока пользователь не нажмёт «ОК»:

Источник

Javascript inside an html attribute

I have a pretty simple query here. I have a view page with an div and a form element. This is how they look.

I need to access the value of candy inside input's attribute (it can be any attribute). I tried the code as I have shown above but that didnt work. I researched on StackOverflow too but couldnt find anything satisfactory. Please help out. Edit: Thank you everyone. I found the answer to that, which I am gonna mark. Also, deleting this question so that it doesnt confuse someone else.

"I need to access the value of candy inside input's attribute (it can be any attribute)." When do you need to do that? Why do you think you need to do it in the markup? What about when the user changes the value? I think you have an X/Y problem here. Also note that value is not a valid attribute for div elements; if you need to embed your own data in attributes, use a data-* attribute.

5 Answers 5

If I assume you want to do this at page load, do it like this

Note 1, custom attributes should have a data- prefix and use .dataset to access its value.

Note 2, for older browsers like IE10 and below, you need getAttribute (as in 2nd sample below).

    
    

Datasets are not compatible with IE10 - getAttribute is compatible with all browsers currently worth supporting

@ScottMarcus you should be using yeah, it was maybe just the wording that got me worried. Maybe you could use , would have not frightened me so much.. 🙂

Do it in JavaScript outside of code but after the objects exist.

Here's an example of how to achieve this:

var candy = document.getElementById('candy').getAttribute('data-value'); document.getElementById('input').value = candy;

As mentioned in the comments, please make sure your JavaScript code is loaded after your markup. There are various ways to do this, including waiting for the dom to load.

@mplungjan: That's a flaw in Stack Snippets (which I reported years ago, but SE didn't care), not in the answer. When you run the snippet, it has them in the correct order.

@mplungjan, the snippet works. This isn't a question about where to put the JavaScript code. The order is how the snippet system on stackoverflow adds the different sections.

document.getElementById('input').value = document.getElementById('candy').dataset.value

This is not how you should be doing this.

JavaScript should be separated out of the HTML completely to avoid a whole host of issues. Including JavaScript in the HTML as you are attempting is a 20+ year old technique that was used before we had standards.

Next, a div element can't have a value attribute. value is only for form fields. But, you can create a data-* attribute, which allows for you to create custom attributes. You can then extract that value using the .dataset property.

// This code would be placed inside of  tags and the whole // thing would be placed just before the closing body tag (). document.getElementById("result").value = document.getElementById('candy').dataset.value;

Источник

Читайте также:  Variable python что это
Оцените статью