What is the difference between setAttribute and dot notation in Javascript? [duplicate] - javascript

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
When to use setAttribute vs .attribute= in JavaScript?
Why do you sometimes set an attribute like this:
x.type = "submit";
and other times like this:
x.setAttribute("type", "submit");
I always figured it didn't matter which way, but I'm having an issue doing this:
x.onClick = save;
but when I switch it to this it works:
x.setAttribute("onClick", "save()");

setAttribute only works on DOM elements and lowercases the attribute name on HTML elements. And you can't use dot notation to assign values to dynamic attribute names.
And there's also this:
Using setAttribute() to modify certain attributes, most notably value
in XUL, works inconsistently, as the attribute specifies the default
value. To access or modify the current values, you should use the
properties. For example, use elt.value instead of
elt.setAttribute('value', val).

Related

JS how to get twitter's name [duplicate]

This question already has answers here:
How to Get Element By Class in JavaScript?
(12 answers)
Closed 9 years ago.
Using JavaScript, we can get element by id using following syntax:
var x=document.getElementById("by_id");
I tried following to get element by class:
var y=document.getElementByClass("by_class");
But it resulted into error:
getElementByClass is not function
How can I get an element by its class?
The name of the DOM function is actually getElementsByClassName, not getElementByClassName, simply because more than one element on the page can have the same class, hence: Elements.
The return value of this will be a NodeList instance, or a superset of the NodeList (FF, for instance returns an instance of HTMLCollection). At any rate: the return value is an array-like object:
var y = document.getElementsByClassName('foo');
var aNode = y[0];
If, for some reason you need the return object as an array, you can do that easily, because of its magic length property:
var arrFromList = Array.prototype.slice.call(y);
//or as per AntonB's comment:
var arrFromList = [].slice.call(y);
As yckart suggested querySelector('.foo') and querySelectorAll('.foo') would be preferable, though, as they are, indeed, better supported (93.99% vs 87.24%), according to caniuse.com:
querySelector(all)
getElementsByClassName
Don't use w3schools to learn something
Refer to MDN for accurate information
Another option is to use querySelector('.foo') or querySelectorAll('.foo') which have broader browser support than getElementsByClassName.
http://caniuse.com/#feat=queryselector
http://caniuse.com/#feat=getelementsbyclassname
You need to use the document.getElementsByClassName('class_name');
and dont forget that the returned value is an array of elements so if you want the first one use:
document.getElementsByClassName('class_name')[0]
UPDATE
Now you can use:
document.querySelector(".class_name") to get the first element with the class_name CSS class (null will be returned if non of the elements on the page has this class name)
or document.querySelectorAll(".class_name") to get a NodeList of elements with the class_name css class (empty NodeList will be returned if non of. the elements on the the page has this class name).
you can use
getElementsByClassName
suppose you have some elements and applied a class name 'test', so, you can get elements like as following
var tests = document.getElementsByClassName('test');
its returns an instance NodeList, or its superset: HTMLCollection (FF).
Read more

Get the outer HTML of a detached JQuery object [duplicate]

This question already has answers here:
Get selected element's outer HTML
(30 answers)
Closed 6 years ago.
I'm creating a html node by jQuery (the sample is of tag <input> but can be of any type):
var x = $("<input>");
Then I add its attributes through a series of .prop() function:
x.prop("id", ...).prop("class", ...);
Now a certain plugin does not support JQuery object, but rather the HTML string so I invoke the plugin through this:
var n = plugin.method1(x.html())
Which I though will work but .html() returns an empty string. Although some said it will be resolved if I append it first on the DOM tree. How can I get its HTML string without appending it first in the DOM tree?
You can use .prop() to get outerHTML property.
x.prop('outerHTML');
var x = $("<input>");
x.prop('id', 'yahooooooooo');
console.log(x.prop('outerHTML'))
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Bit simpler to index the HTMLElement behind it and access the outerHTML property like this:
x[0].outerHTML

JQuery: find element whose class contains value of variable [duplicate]

This question already has answers here:
How to use JavaScript variables in jQuery selectors?
(6 answers)
Closed 7 years ago.
I searched high and low now but I can't figure out how to get this to work:
I need to get the element whose class name contains a number that I pass with a variable.
For better understanding: This is inside a "click" event on a gallery. Whenever an img is clicked I search for the src, see which number the string contains and then want to find the matching p whose class contains the same number. So I can manipulate the matching text to the picture that is currently displayed (Since the plugin I use strips away any id or class I can only identifiy a picture by its source name).
So far it does work if I directly put the number in as a String. Like this:
var team_t = $(this).find("img").attr("src");
for(n = 1; n <=6; n++ ){
if(team_t.indexOf(n) != -1)
{
$('#text_content').find("p[class*='3']").css("background-color", "red");
}
}
But instead of "3" I want it to get the number that the variable n holds. I tried this but it did not work:
$('#text_content').find("p[class*=' + n + ']").css("background-color", "red");
Actually it didn't work with any kind of variable I tried to pass. I also saw and tried examples that use contains( ) or hasClass( ) and others.. but nothing worked for me. I'm not extremly familiar with the syntax though.
How do I have to write this so it takes the variabel as a string?
If I do alert( n ) it shows the correct number, so that's not the problem.
You were on the right track with string concatenation, you just didn't get all the way outside the string:
$('#text_content').find("p[class*='" + n + "']").css("background-color", "red");
// Change is here -----------------^- and -^
In your attempt, the + n + was still in the outer quotes, and so was used literally in the selector (making it fail).
That said, if you have any control over the DOM structure (but it sounds like you may not), there's probably a better way. For instance, you could put a data-* attribute on the element that gives an appropriate selector for the p element (possibly even by id, but that's just one option).
You might also want to end the loop once you've found the index, by putting break; on the line after the line setting the red color.
Finally: You might want to use a class to add the red color rather than mixing your presentation into your JavaScript code.

Removing $() jQuery wrapper to just get raw JS element [duplicate]

This question already has answers here:
How to get a DOM Element from a jQuery selector?
(4 answers)
Closed 8 years ago.
Random just out of curiosity question:
Let's say for whatever reason I get an element back from a function
$(element)
But I want to remove the $( __ ) jQuery wrapper to leave the regular DOM Element:
element
Is this possible? (I'm sure it'd be smart to test $(element).length() to make sure it isn't more than 1 thing inside beforehand too...
jsFiddle
var firstElem = $(element)[0];
or
var firstElem = $(element).get(0);
Calling get() without an index gives you an array of the elements.
Reference: jQuery get()
DOM elements are stored as properties at numeric zero-based indices, so you access them just like you would for any other object.
$jqObj[0];
Or get a full Array of elements using toArray()
$jqObj.toArray();
Fiddle: http://jsfiddle.net/xHj5d/2/
removeJWrapper($('#ohHeyo'));
function removeJWrapper (el) {
console.log(el[0]);
}

How to Determine CSS selector on a DOM object? [duplicate]

This question already has answers here:
How to get an HTML element's style values in JavaScript?
(5 answers)
Get Element StyleSheet Style in JavaScript
(2 answers)
Closed 5 months ago.
I have an element such as element = document.getElementyById("myElement");
Now, let us assume that there is some CSS applied on it through various methods such as #id, .class, and tagName.
We know that #id has priority over .class and .class has priority over tagName. I want to determine which of the above method is applied on that element i.e. I want to see if is has CSS applied on it using id, class, or tag. How would I find that out? Is there any JavaScript Library available for that?
Go through the document.styleSheets object, iterate over each styleSheet object, then each rule. You will then have to parse the selectorText property, essentially writing your own CSS parser while maintaining an internal array on the specificity of each selector.
Compare the specificity of the current rule with the previous ones, then determine which property override which. After all that, you'll still need to check for inheritance - go through each of the parent of the element in question and look for properties that can be inherited, and add them to this list if they're not already set on the children. This also means that you'll need to maintain a set of properties that inherits.
If you haven't realised, this is quite an undertaking. Why not just go and use whatever developer tools that are available for your browser and look at the CSS rules provided by those instead.
Why dont you check
element = document.getElementyById("myElement");
if (element.tagName != "") { ... }
if (element.id != "") { ... }
if (element.className != "") { ... }

Categories

Resources