Tell me more ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

I execute

document.getElementsByTagName('img')[0]['!abc'] = "abc";

to set "!abc" attribute to one image element.

When I try to get this attribute in content script, the result is null.

But when I try to get it in document console, the result is "abc".

share|improve this question
Your code doesn't set an attribute. It sets a property on the DOM element. (Frequently called an "expando" property.) While some properties are reflected attributes, that's a small set of properties defined by the DOM. Your expandos don't magically become attributes. – T.J. Crowder 7 hours ago
I execute "document.getElementsByTagName('img')[0]['!abc']" in content script, it returns null. but the result is "abc" in document console with the same code. My goal is to get, not to [email protected] – Leslie Wu 7 hours ago
@ Leslie: If your got is to get, why are you showing a set operation? – T.J. Crowder 7 hours ago
@LeslieWu Make sure that you are looking at the correct context in the developer tools. If it's not a matter of debugging, but implementation, you have to inject code in the page, which handles the "get" operations for your content script (see this detailed answer by apsillers). – Rob W 5 hours ago

2 Answers

Use setAttribute();

var myImg = document.getElementsByTagName('img')[0];
myImg.setAtrribute("attrib_name", value);
share|improve this answer
+1 It's more powerful, though, if you actually use the example from the post. E.g.: document.getElementsByTagName('img')[0].setAttribute("!abc", "abc"); Also if you explain why the OP's code didn't work. – T.J. Crowder 7 hours ago
I execute "document.getElementsByTagName('img')[0]['!abc']" in content script, it returns null. but the result is "abc" in document console with the same code. My goal is to get, not to set. – Leslie Wu 7 hours ago
Well it could give you mixed results I have not used this approach ever. The above approach is the one preferred. – pvnarula 7 hours ago

You can define a function that do like:

function setElementAttrbute(tagname,index,attrName,value){

    var elements = document.getElementsByTagName(tagname); // returns kind of array
    elements[index].setAttribute(attrName,value); 

}

When you would like to use array-methods like (slice,push,pop,shift,unshift), you can cast it by doing this:

document.getElementsByTagName(tagname); // returns kind of array that does not have got array.-methods like above.
elements = Array.prototype.slice.call(elements); // returns real array
share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.