How to get the parent element too with getElementByClassName? - javascript

I have certainly extremely simple problem and I'm a little ashamed of not being able to solve it by myself.
HTML:
<div>
<ul class="test">
<li>1</li>
</ul>
<ul class="test">
<li>2</li>
</ul>
</div>
JavaScript:
var tests = document.getElementsByClassName('test')[0].innerHTML;
alert(tests);
jsFiddle:
Try it
Currently, the result shows me <li>1</li>.
This is not what I want. I want the result to be <ul class="test"><li>1</li></ul>.
I tried using .parent() (I can use jQuery) but it gives me all <ul> tag while I just want the first. I also know that I could use some .split() but it is surely not the adviced way.
I thought the problem might be coming from the .innerHTML, there is a function that would allow me to recover also the target element, and not just his children?

Just use outerHTML instead of innerHTML
var tests = document.getElementsByClassName('test')[0].outerHTML
Check Fiddle
You can do the same with jQuery. $.each to iterate over the elements and then use this so that it only points to that elements instead of all the elements with that class
jQuery
var $tests = $('.test');
$tests.each(function() {
console.log(this.outerHTML)
});
jQuery Fiddle

Related

Inserting HTML into tag using JavaScript

I'm having a problem with JavaScript/jQuery at the moment where I'm trying to access the element inside the h4 element in my code. I'm doing this because I would like to dynamically display to the user how many guides are available in each "h4" section. For the PC section, it should display "4 reviews available" and for the Xbox One section, it should display "3 reviews available". However, both say " reviews available", and I'm assuming it's because I'm not using the jQuery functions properly. Here's the HTML code:
<h4><li class="console">PC (<span class="number"></span> reviews available)</li></h4>
<div class="gameList">
<ul>
<li class="game">Guide #1</li>
<li class="game">Guide #2</li>
<li class="game">Guide #3</li>
<li class="game">Guide #4</li>
</ul>
</div>
<h4><li class="console">Xbox One (<span class="number"></span> reviews available)</li></h4>
<div class="gameList">
<ul>
<li class="game">Guide #1</li>
<li class="game">Guide #2</li>
<li class="game">Guide #3</li>
</ul>
</div>
And here's the jQuery/JavaScript code:
$("h4").each(function() {
var node = $(this).children().children(); // gets node that has "number" class
var count = $(this).next().children().children().length; // gets number of li tags
node.innerHTML = count;
});
I tested whether or not it's properly getting the correct node and count by using the alert function for JavaScript, but for some reason, node.innerHTML = count won't display the contents of "content" properly in the element. Rather, it just displays a blank. Does anyone know why?
Its a jquery object not a DOM one..use this...
node.html(count);
node is a jQuery object here. It does not have "innerHTML". Instead you can use one of these:
node.html(count);
node.get(0).innerHTML = count;
node.get(0) will give you first DOM object from jQuery one.
A good practice is to prefix or suffix all jQuery objects with $ (e.g. $node), so that you will always know if a variable is meant to be a jQuery object.
use find() lot more cleaner and readable
$("h4").each(function() {
var $this=$(this);
var node = $this.find('.number');
var count = $this.next().find('li').length; // gets number of li tags
node.text(count); //or html()
});
and you have come invalid HTML li in h4 make sure you change that
working fiddle here
Do not use .children().children().
Only one .children() would do.
$(this).children('.game');
Also innerHTML is plain javascript. use .html(value) as node is JQuery Object.
$("h4").each(function() {
var node = $(this).children('.number');
var count = $(this).next().children('li').length;
node.html(count);
});
Reference to JQuery APIs:
.html()
.children()
$("h4").each(function() {
var $spanNumber = $('.console .number', this),
gameListCount = $(this).next().find('ul li').size();
$spanNumber.text(gameListCount)
});
You may use this also,
$("h4").each(function() {
var node = $(this).find('.number');
var count = $(this).next().find('.game').length;
node.html(count);
});

Javascript get node innertext based on hierarchy

My HTML looks like
<li value="0">
<a href="#">
<span>DATA TO GET</span><![if gt IE 6]>
</a><![endif]><!--[if lte IE 6]><table><tr><td><![endif]-->
<ul>
<li value="0">
<a onclick="return showPane('SomePane',this)" href="#">ACTIVE NODE</a>
</li>
</ul>
This html is produced using xsl. Now i want to get the data inside span tag using javascript. I tried the following:
var nameParent = activeTab.parentNode.parentNode.previousSibling;
window.alert(activeTab.innerHTML);
window.alert(activeTab.parentNode.parentNode.previousSibling.childNode);
Here the variable activeTab is passed the anchor that contians the text ACTIVE NODE.The first alert gives proper data i.e ACTIVE NODE but the second alert says undefined.
I think i am travsring the correct path and proper elements. Can some body point out what is wrong here and what else i can do to get the required data.
Thanks in advance.
Try this
var nameParent = activeTab.parentNode.parentNode;
window.alert(activeTab.innerHTML);
window.alert(nameParent.parentNode.children[0].children[0].innerHTML);
I stronly suggests use jQuery in your Project, it provides methods for easy navigation among dom elements like
.find() and .children(), .parent for more readable code.
Thanks
Try using firstChild instead of childNode:
var nameParent = activeTab.parentNode.parentNode.previousSibling;
window.alert(nameParent.firstChild.innerHTML);

Convert jQuery selector to HTML for a new DOM element

I want to implement a jQuery plugin that converts a selector to HTML. I understand that the mapping between these two syntaxes is many-to-many, but simple selectors would be easy to covert to HTML.
Example:
$('div#my-id.my-class').create();
might generate:
<div id="my-id" class="my-class" />
EDIT:
The purpose is to create an element if the selector returns an empty set, without having to add redundant code.
var jqs = $('div#my-id');
if(jqs.length===0) jqs = jqs.create();
var elementWillAlwaysBeThere = jqs.get(0);
i know this might not be what you are lokking for. the project zen coding is about using a css like syntax to create dom structurs. so i think lokking at there source is going to help you alot, even thou its not pure css selectores.
div#wrapper>ul#imageSlider>li.image$*3 compiles to:
<div id="wrapper">
<ul id="imageSlider">
<li class="image1"></li>
<li class="image2"></li>
<li class="image3"></li>
</ul>
</div>
so if you where to use the jQuery port you can do youre example like
$.zc("div#my-id.my-class") again resulting in
<div id="my-id" class="my-class"></div>
happy source reading

jquery replace all <ol> with <ul>

Given the following dom structure I would like to transform an ordered list to an unordered list.
<div class="wrapper">
<ol>
<li><div>foo</div></li>
<ol>
<li><div>bar</div></li>
</ol>
<li><div>batz</div></li>
</ol>
</div>
What is the best way to do this?
You should use jQuery replaceWith.
ok i had to work from the inside to the outside, only replaceWith wasn't working because it replaced only the outer tags and didn't replace the inner ones, so i solved it this way:
$($('.wrapper').find('ol').get().reverse()).each(function(){
$(this).replaceWith($('<ul>'+$(this).html()+'</ul>'))
})
if someone has a better solution i would be glad to hear it.

What is the difference between .empty().append() and .html()?

Using jQuery, what's the performance difference between using:
$('#somDiv').empty().append('text To Insert')
and
$('#somDiv').html('text To Insert')
?
$('#somDiv').html(value) is equivalent to $('#somDiv').empty().append(value).
Source: jQuery source.
.html will overwrite the contents of the DIV.
.append will add to the contents of the DIV.
difference between append() and html() in jQuery
.append() and .html() are the most useful methods in jQuery. But these are far different from one another, .append() add some value to the existing one. Where .html() do the same but it removes the old value first.
Here is an example:
<ul id="test">
<li>test</li>
</ul>
Now I will use .append() to add one <li>, For that I will write:
<script type="text/javascript>"
jQuery("#test").append("<li>test1</li>");
</script>
The output of this jQuery will be:
<ul id="test">
<li>test</li>
<li>test1</li>
</ul>
Now if I use .html() to add one <li>, For that I will write:
<script type="text/javascript>"
jQuery("#test").html("<li>test1</li>");
</script>
The output of this Script will be:
<ul id="test">
<li>test1</li>
</ul>
Here in this example .append() add one extra <li>, whether .html() removes the old one with new one. This is the main difference between .append() and .html() in jQuery.
In simple words:
$('#somDiv').append('blabla')
works like this:
<div id='somDiv'>some text</div>
becomes:
<div id='somDiv'>some textblabla</div>
And innerHTML replaces the contents, so it becomes this:
<div id='somDiv'>blabla</div>
The correct syntax is
$("#somDiv").html("<span>Hello world</span>");

Categories

Resources