0

If I create a new DOM element with Javascript document.createElement, is there a way to use jquery function attr() to change the element's attribute?

0

3 Answers 3

2
var element = document.createElement(tagName);
$(element).attr('foo', 'bar');
Sign up to request clarification or add additional context in comments.

Comments

1

you can use javascript like :

var link = document.createElement('a');
link.setAttribute('href', 'mypage.htm');

or jquery

$(link).attr('href', 'mypage.htm');

2 Comments

(for the first method) if you will add an event (like onclick). maybe you should just use link.onclick instead of link.setAttribute source = justinfrench.com/notebook/javascript-setattribute-vs-ie
@yilmazhuseyin: Yeah, that's why I always recommend to use DOM properties over setAttribute.
1

Of course you can, but compare:

var element = document.createElement('input');

$(element).attr('type', 'button');

// vs.

element.type = 'button';

IMO I would simply use the second approach, staying away from the IE's buggy element.setAttribute method.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.