mart1n
mart1n

Reputation: 6213

jQuery .attr() does not set custom attribute and value

I'm simply setting a custom attribute in the document.ready function in the following way:

$(document).ready(function(){
    $("div.para, pre.screen, div.figure, pre.programlisting").attr("data-test-ID", "hello");
});

When I reload the HTML and look at the source, there is no trace of such attribute anywhere. Any ideas? I'm really stuck on this and can't figure it out.

Upvotes: 1

Views: 3963

Answers (1)

Eventor
Eventor

Reputation: 46

This in fact works, you have to look at the DOM (Document Object Model) as any changes done by javascript do not directly edit the page source. the source will always be exactly what the server sent.

$(document).ready(function(){
    $("div.para, pre.screen, div.figure, pre.programlisting").attr("data-test-ID", "hello");
    $("#result").text("para contains :" + $("div.para").attr("data-test-ID"));//view value
});

Working Example

Using Chrome or Firefox, Right Click on the element and click Inspect Element to view the values set by the DOM to the element

You code is correct and the value is infact set :)

Upvotes: 2

Related Questions