Get content from id inside id? - javascript

I have HTML like:
<div id='content'>
<div id='price'>$100</div>
<div id='another'>something</div>
</div>
I can get content from id="content" like.
vl = document.getElementById("content").value;
In this id, I have another id="price". But I cannot get directly content from id="price".
How can I get content from id="price" through id='content'.Thank you.

jQuery:
$("#price").text();
javascript:
document.getElementById("price").innerHTML;
DEMO

You can use as below :
vl = document.getElementById("price").innerHTML;
JSFiddle - Check it out
YOu can also use jquery using .html() or .text() method

Try,
$('#content').html().find('#price').html();

Try this,
var parent = document.getElementById('content');
var childNodes = parent.childNodes;
for(var i = 0, len = childNodes.length;i<len;i++){
if(childNodes[i].id === "price") {
alert(childNodes[i].innerHTML);
}
}

Using jquery,
$("#content > #price").text();

You can get value of price directly as :
v2 = document.getElementById("price").value;

using Jquery,
v1= $('#content').html();
v2=v1.find('#price');
v3=v1.find('#another')

Try this out:- http://jsfiddle.net/adiioo7/C3C4x/1/
var price = document.querySelector("#content #price").innerHTML;
console.log(price);

IDs should only be used when there is one of that item on the page. You will have no other chance as to re-assign your IDs, or alternatively using the class attribute.
Try this way to select,
var vl = document.getElementById("content").getElementsByClassName("price")[0];
HTML
<div id='content'>
<div class='price'>$100</div>
<div class='another'>something</div>
</div>

You need to access the child element through parent element... that is your question right.. i solve it with jquery DEMO
$(document).ready(function(){
var tem = $('#content').children('#price').text();
alert(tem);
});

Related

clone or append a variable in a new div?

I have this Html <h1 class="count" role="status">Search results 546</h1>
I'm trying to clone only the numerical '546' of that div and display it inside another div 'h2.count'
I manage to call only the numerical value in an alert via:
var price = $('h1.count').text();
var parsedPrice = parseFloat(price.replace(/([^0-9\.])/g, ''));
alert(parsedPrice.toFixed(0));
Otherwise , when i try to make it display in the div h2.count instead of an alert, it is not working.
I have try the below:
var price = $('h1.count').text();
var parsedPrice = parseFloat(price.replace(/([^0-9\.])/g, ''));
$parsedPrice.appendTo('h2.onlycount');
Any thought of what i am doing wrong ?
Thanks a lot guys !
I guess that your two html elements are unique so, using id's instead of classes (and native js), try this :
html :
<h1 id="count">Search results 541</h1>
<h2 id="onlycount"></h2>
js :
var price = document.getElementById('count').innerText;
var parsedPrice = parseFloat(price.replace(/([^0-9\.])/g, ''));
document.getElementById('onlycount').innerText = parsedPrice;
https://jsfiddle.net/f3rj2bnv/
And if you want to keep on using jQuery (replace "#" with "." if you want or have to use classes instead of ids in your html elements) :
var price = $('h1#count').text();
var parsedPrice = parseFloat(price.replace(/([^0-9\.])/g, ''));
$('h2#onlycount').text(parsedPrice)
The content used by .appendTo() should be
"a selector expression or as markup created on the fly"
Since in your example neither is true, try this:
var price = $('h1.count').text();
var parsedPrice = parseFloat(price.replace(/([^0-9\.])/g, ''));
$('h2.onlycount').text(parsedPrice);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<h1 class="count" role="status">Search results 546</h1>
<h2 class="onlycount" role="status"></h1>
Can use text(function)
$('h2.onlycount').text(function(_, existingText){
return existingText + $('h1.count').text().replace(/([^0-9\.])/g, '');
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<h1 class="count" role="status">Search results 546</h1>
<h2 class="onlycount"></h2>

How to append an element before another using Javascript?

I tried following the a wiki and looking into multiple questions here but I still have problems with insertBefore..
This is my sample:
<div id="container">
<span id="first">1</span>
<span id="second">2</span>
<div id="third">3</div>
<div id="forth">4</div>
</div>
<script>
topbar = document.getElementsById("container");
boardlist = document.getElementsById("first");
bmcontainer = document.createElement("span");
bmcontainer.setAttribute("id", "zero");
bmcontainer.innerHTML("0");
topbar.inserBefore(bmcontainer, boardlist);
</script>
I want to append the span#zero before the span#first. What am I doing wrong? I'm trying to not use jQuery, so I'm looking for a totally javascript solution.
Node.insertBefore() is the answer.
var insertedNode = parentNode.insertBefore(newNode, referenceNode);
If you have Parent Node, then you should use ParentNode.prepend()
ParentNode.prepend(nodesToPrepend);
Take a look # mentioned links for full documentation and examples.
Update
You have some issues in your code (typo and wrong usage of innerHTML), here is fixed code.
HTML
<div id="container">
<span id="first">1</span>
<span id="second">2</span>
<div id="third">3</div>
<div id="forth">4</div>
</div>
JS
var topbar = document.getElementById("container"),
boardlist = document.getElementById("first"),
bmcontainer = document.createElement("span");
bmcontainer.setAttribute("id", "zero");
bmcontainer.innerHTML = "0"; // innerHTML is not a function, it's a property
topbar.insertBefore(bmcontainer, boardlist);
jsfiddle
Notice that InnerHTML is not a function, it's a property, read more about that here: Element.innerHTML
Prepend pure javascript
MDN article on insertBefore()
var el = document.getElementById('thingy'),
elChild = document.createElement('div');
elChild.innerHTML = 'Content';
// Prepend it
el.insertBefore(elChild, el.firstChild);
Source: http://clubmate.fi/append-and-prepend-elements-with-pure-javascript/#Prepend
Also, the jQuery prepend() Method
You can read about it here and here.
You can use the insertAdjacentElement function.
var boardlist = document.getElementById("first"),
bmcontainer = document.createElement("span");
bmcontainer.setAttribute("id", "zero");
boardlist.insertAdjacentElement('beforebegin', bmcontainer);
Element.insertAdjacentElement

get html from a variable by id

i have a variable name value in my javascript code that contain html data.i want to get the data inside form specific id that is inside #myDiv
var value="<div >
<p class="">Hi cname#gmail.com</p>
<br/>
<br/>
<br/>
<div id="myDiv">
sgdhsagdhagh
dhsajdgasj
cjzjcg
</div>
</div>"
Thanks
You should create a DOM element, then traverse up to it and get html() or .text()
var value = '<div >\
<p class="">Hi cname#gmail.com</p>\
<br/>\
<br/>\
<div id="myDiv">\
sgdhsagdhagh\
dhsajdgasj\
cjzjcg\
</div>\
</div>';
alert($(value).find('#myDiv').html())
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
If you need to get parent element, then use
alert($('<div />', {html: value}).find('#myDiv').html())
How about you do like this?
var variable = "stuff n things";
document.getElementById( 'myDiv' ).innerHTML = variable;
Thats the native way :)
EDIT:
if you want to get the data you just do like this:
var variable = document.getElementById( 'myDiv' ).innerHTML;
That will give you the markup of whats inside the div.
Or use document.querySelector("#myDiv") to get the first match on the selector.querySelectorAll returns array.
You can use the HTML of the value variable to create an jQuery object. From this object you can search for the element with the id, and get its HTML content:
var html = $(value).find('#myDiv').html();
console.log(html); //sgdhsagdhaghdhsajdgasjcjzjcg
Or a pure javascript implementation:
var el = document.createElement('div');
el.innerHTML = value;
var html = el.getElementById('myDiv').innerHTML;
console.log(html); //sgdhsagdhaghdhsajdgasjcjzjcg
Using plain Javascriptuse:
document.getElementById("myDiv").innerHTML;
Using jQuery:
$("#myDiv").html();
There are Two ways- Angular way-
var elem = angular.element(value);
var innerDive=elem[0].getElementById('myDiv');
var text= angular.element(innerDive[0]).innerText;
Jquery-
var text= $(value).find('#myDiv').text();

jquery - how can I select element after '.first()' using?

How can I select html tag after using jquery function called .first() ?
HTML
<html>
<head> </head>
<body>
<div>
<a>
<img id="#hello">
</a>
</div>
<div></div>
</body>
</html>
JS (JQuery)
var elemFirst = $(div).first();
var selectImg = elemFirst.$('img#hello');
// var selectImg = elemFirst.find('img'); <- It working but I want to select manual
selectImg.addClass('some-css');
With Respect
You can use $('child','parent') selector,
var elemFirst = $('div').first();
var selectImg = $('#hello',elemFirst); //or just $('img',elemFirst);
Also, your id has a #, it should be just id="hello".
If you need to keep this value in Id, use
var selectImg = $('img[id="#hello"]',elemFirst);
You can use find():
var selectImg = elemFirst.find('img#hello');
But you have an id of the image, so, you just can do this:
$('img#hello')
Because id is unique.
Use find()
elemFirst.find('img#hello');
This will search for direct and nested elements with the provided selector.
Alternatively, you can do
$('div:first #hello')
or even just
$('#hello')
since you are using an id which should be unique.
As in html the id be unique in html so striaghtly write
$("#\\#hello").addClass('some-css');
or
var selectImg = elemFirst.find('img[id="#hello"]');
Fiddle

Find div by value attribute and get html

I have some hidden divs with id's in html value attr. I want to find the div by value and get it's html. The problem is that my jQuery code returns undefined.
$( ".showComments" ).click(function() {
var id = $(this).closest('button').siblings('.writeComment').val();
var obj = $("#myDivs[value=id]").html();
alert(obj);
});
<div id='myDivs' value = '".$id."'>
<div>
<h3></h3>
<p></p>
</div>
</div>
I get the id correctly, but problem is when i tried get the divs html.
try:
var obj = $("#myDivs[value='"+id+"']").html();
console.log(obj);
Okay, that is wrong because it'll search for value="id" instead value="1" for example:
so you should do this:
var obj = $("#myDivs[value=" + id + "]").html();

Categories

Resources