How to get the name of an element with Javascript? - javascript

I'm trying to get the name of an element in Javascript. Meaning if the element is <div />, then "div" would be returned. If it's <img src="" /> then "img" would be returned. I'm using jquery to select a bunch of elements and then calling a custom function on all of them. Within that function I want to know what I'm dealing with. How do I do this?
Seems like a simple thing. And I think I've done it before but I just can't find it. Google results keep giving me "get element by name" no matter how I phrase it.

Use nodeName (see this note about tagName):
"My advice is not to use tagName at all.
nodeName contains all functionalities of tagName, plus a few more. Therefore nodeName is always the better choice."

tagName or nodeName

$(selector).each(function() {
switch (this.tagName) {
// Handle cases
}
});

You want element.nodeName Or, within jQuery:
$(".includeMe").each(function(){
alert(this.nodeName);
});
<img class="includeMe" src="puppies.jpg" />
<div class="includeMe">Hello World</div>
<p class="includeMe">Don't forget me as well</p>

For element.tagName and element.nodeName return the name of your tag, in uppercase.
If you want it in lowercase, just use element.tagName.toLowerCase() or element.nodeName.toLowerCase().

Related

Move element before second to last h2 with jQuery

I am trying to move an elmement with class .books_inarticle_list from its native possition tu just before the second to last H2.
I am using the following which is not working:
$('.books_inarticle_list').insertBefore('#content_column > h2:nth-last-child(2)');
On the other hand something like this works:
$('.books_inarticle_list').insertBefore('#content_column > h2:nth-of-type(6)');
So the issue must be with the nth-last-child() selector, but I don't see what it might be.
Does anyone see anything wrong with that code or knows an alternative way to move that element to just before the second to last H2 tag?
Try the .get() method, which supports negative numbers to go in reverse.
$('.books_inarticle_list').insertBefore($('#content_column > h2').get(-2));
Edit On second thought, it makes more sense to follow your own examples and use the :nth-last-of-type() selector, which will go in reverse.
$('.books_inarticle_list').insertBefore('#content_column > h2:nth-last-of-type(2)');
The reason :nth-last-child() isn't working for you is because that, and :nth-child(), refers to the number of siblings they have in the DOM, not the list of elements returned by the selector.
You'd be better off providing your HTML for the optimal solution, however given your question I'd suggest something like the following:
var $h2s = $("#content_column > h2");
var $secondToLast = $h2s.eq($h2s.length-2);
$('.books_inarticle_list').insertBefore($secondToLast);
I passed on using nth-child just because that will be thrown off any time you modify your HTML structure.
Note, :nth-* selectors use 1-based indexing. You can use :nth-last-of-type() selector with 2 as parameter to selector second from last element of that type, chain .before() with $(".books_article_list") as parameter.
$("#content_column h2:nth-last-of-type(2)").before($(".books_article_list"));
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="books_article_list">books</div>
<div id="content_column">
<h2>0</h2>
<h2>1</h2>
<h2>2</h2>
<h2>3</h2>
<h2>4</h2>
<h2>5</h2>
<h2>6</h2>
</div>
i prefer to use ":eq" even ":nth-of-type". So will be :
$('.books_inarticle_list').insertBefore('#content_column > h2:eq('+($('#content_column > h2').length()-2)+')');

jQuery span class selector

I have a span with a text inside it like :
<span class="characters-count">(160 Characters Left)</span>
given the span a class in this case .characters-count , when i tried class selector using jQuery to get the text inside span :
$(".characters-count")[0].text();
it returns undefined !
However this selector works well :
$("span.characters-count").text();
anyone can explain what is happening ?
$("span.characters-count").text();
In our case you work with jQuery Object that has text method
$(".characters-count")[0].text();
In this case you work with actual DOM element (like document.getElementByClassName('characters-count')[0]) that does not have text method
Use
$(".characters-count").text();
Demo
console.log($(".characters-count:first").text())
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<span class="characters-count">(160 Characters Left)</span>
try something like this:
$(".characters-count:first").text()
Check here, why it was not working for you.
//This will return dom element, so it doesn't have `text()` method, that's why it was throwing error for you.
console.log($(".characters-count:first")[0]);
// This will return object of an element, you can use jQuery selectors to get first element from collection and set text to it
console.log($("span.characters-count"));
console.log($("span.characters-count:first").text
);
you need to use innerText instead of text() when you use $(".characters-count")[0] check DEMO
$(".characters-count")[0].innerText

Get the parent HTML element of certain type with JS

My code looks like this, in closeup:
<h2>
<span class="stuff">[<a id="someid">stuff</a>]</span> <span class="moreStuff">Another test</span>
</h2>
I've found a way to select my a element, and attach an id to it. What I need to do now is select its parent <h2> element, but not the <span> element. How can I do that (JQuery allowed)?
Edit: when I retrieve the selected <a>s, I get an array of them (there's lots of these structures on my page). When I try to write myArray[someIndex].closest("h2"), it says that the element does not have a closest() method. How would I go about this?
One ways is to use the .parents() method of jQuery, with a selector. Something like this.
$("#someid").parents("h2");
Update:
You can use the .closest() method with a selector, to only get the closest parent that match the selector.
$("#someid").closest("h2");
Update 2:
It would be a bit more work to do it with plain JavaScript. Not sure if it is the most efficient, but one way would be to select the element with document.getElementById() and then get a reference to its parent through the parentNode property. Then you would have to check if it is an h2 element, and if not, look at that elements parent node, and so on.
You could check the jQuery source and see how they have implemented the closest method.
I just needed the same thing. here a vanilla javascript variant:
function findParent(startElement, tagName) {
let currentElm = startElement;
while (currentElm != document.body) {
if (currentElm.tagName.toLowerCase() == tagName.toLowerCase()) { return currentElm; }
currentElm = currentElm.parentElement;
}
return false;
}
The <h2> is not the parent of the <a> but it is an ancestor, use .closest() to select it
$("#someid").closest("h2");
try use .parent() for get exactly double or more level up the DOM tree.
$("#someid").parent().parent();

jQuery first of type selector?

How would I select the first <p> element in the following <div> with jQuery?
<div>
<h1>heading</h1>
<p>How do I select this element with jQuery?</p>
<p>Another paragraph</p>
</div>
Assuming you have a reference to the div already:
$(yourDiv).find("p").eq(0);
If the first p will always be a direct child of the div, you could use children instead of find.
Some alternatives include:
$(yourDiv).find("p:eq(0)"); //Slower than the `.eq` method
$(yourDiv).find("p:first");
$(yourDiv).find("p").first() //Just an alias for `.eq(0)`
Note that the eq method will always be the fastest way to do this. Here's the results of a quick comparison of the eq method, :eq selector and :first selector (I didn't bother with the first method since it's just an alias of eq(0)):
$('div p:first')
answer was too short to post without this useless sentence.
Edit
This is definitely a slow option. After looking at Jame's speed test, it looks like jQuery selectors work best when they piggy back off of css selectors.
$("div p").first();
or $('div p:first');
Reference: http://api.jquery.com/first/
Keep in mind that first() matches only a single element, the :first-child selector can match more than one: one for each parent.
You almost know the answer (from your post title). There is a selector in jQuery called :first-of-type. Use it to find and add class to the first p tag automatically, like so:
$("div p:first-of-type").addClass('someClass');
$('div p').first()
Should work. I think.
This should work
$( "div p:first-of-type" ).css( "font-size: 10px" );
The above code finds the first paragraph in the div as #Denver pointed and changed its fonts-size to 10px
Here is an example that explains even more about jQuery first-of-type selector

jQuery selector by classname minus classname

I have the following jquery line in a click event of a p element:
$(this).nextUntil('.Maintheme not:.Document')
I would like to get all the next elements with class .Maintheme but not .Document.
To explain myself a little better, this is the html that i have:
<div id="DocumentContents">
<p class="Maintheme">ParentTheme1</p>
<p class="Document">Document1</p>
<p class="Maintheme">ParentTheme2</p>
<p class="Subtheme">SubTheme1</p>
<p class="Document">Document1</p>
<p class="Document">Document2</p>
<p class="Document">Document3</p>
<p class="Subtheme">SubTheme2</p>
<p class="Document">Document1</p>
</div>
Having this html content i would like that when you click in a p element if there is not subthemes then show documents. Else if there are subthemes with documents below, just show the subthemes, and if you click in a subtheme show the next documents.
Something like this?
Example: http://jsfiddle.net/ZSCs3/
$('p:not(.Maintheme)').hide();
$('.Maintheme').click(function() {
var $this = $(this)
if ($this.next('.Subtheme').length) {
$this.nextUntil('.Maintheme').filter('.Subtheme').toggle();
} else {
$this.nextUntil('.Subtheme,.Maintheme').toggle();
}
});
$('.Subtheme').click(function() {
$(this).nextUntil('.Subtheme,.Maintheme').toggle();
});
You should use .nextAll().
var $themes = $(this).nextAll('.Maintheme');
You have to do some if-statements from there to create the logic you want.
if($themes.length){
}
else{
}
Anyways, this looks odd to me. You should use a nested list for instance to display such kind of structures.
Ref.: .nextAll()
You don't have the not syntax quite correct but it's not clear to me exactly what you are asking for so I won't try and correct it for you, just point you at the reference. I agree that this looks a bit off anyway.
I think that the not() jQuery selector is more suitable for your case since the nextUntil() selector will stop gathering the elements with the Maintheme class on the first occurence of p tag styled with Document class. Hence you can use code slice like this:
$(this).not(':.Maintheme').css(hidePtagsWithDocumentclass);

Categories

Resources