document.getElementById like function for a particular div - javascript

document.getElementById will search th whole document and return the result but here i want the same function for a particular div as i want to search the specific div for an id and based on that i want to execute
here is my code
if(document.getElementById('myId') ) // but it return the result from whole div
{
// Do something
}
else {
// do something else
}
i want something like
if(document.getElementById('myId') in specific div) \\ how to do this

Let say, you are looking for an element(div) with id "childId" within parent div with id "parentId". The Jquery code would be:
$("#parentId").find("#childId")
As a shortform, you can even do
$("#parentId #childId")
Since the above statement will find children in any depth, if you would want a direct child search, (first level child)
$("#parentId > #childId")
Generally ids are unique within the page (or atleast are recommended to be :) ). In such a case, you can directly do
$("#childId")
and still get the child element.
Whichever applies.

You want to search for a specific id for all div
I assume that you know the id you want to search
You can itenerate the document.getElementsByTagName('div') like this
var myID = 4;
for (var i = 0; i < document.getElementsByTagName('div').length; i++){
var res = document.getElementsByTagName('div')[i+1].id;
if(res == myID){
document.body.innerHTML = res;
break;
}
}
And this would be your HTML look like:
<div id="1"></div>
<div id="2"></div>
<div id="3"></div>
<div id="4"></div>
<div id="5"></div>
<div id="6"></div>
See Demo here
Or I further assume that yor HTML code is look something like this:
<div id="myId">
<div id="1"></div>
<div id="2"></div>
<div id="3"></div>
<div id="4"></div>
<div id="5"></div>
<div id="6"></div>
</div>
Then you can itenerate the document.getElementById('myId').getElementsByTagName('div') like this:
var myID = 3;
for (var i = 0; i < document.getElementById('myId').getElementsByTagName('div').length; i++){
var res = document.getElementsByTagName('div')[i+1].id;
if(res == myID){
document.body.innerHTML = res;
break;
}
}
And See Another Demo Here

id attributes should be unique, so searching an element with an id within another element it's the same as search for that id directly in the whole DOM.

You can return an element only if it is a child of a particular element by using a querySelector:
document.getElementById('evalBar').querySelector('#button_2');
/* returned value: (html BUTTON)
[object HTMLButtonElement]
*/

You could use the querySelector function. IMPORTANT: check browser compatibility!
https://developer.mozilla.org/en-US/docs/Web/API/document.querySelector
Example:
<div id="foo">
<div id="bar">
this is foo-bar
</div>
</div>
<script>
var bar = document.querySelector("#foo #bar")
alert(bar.innerHTML); // result: alert message "this is foo-bar"
</script>

Related

Counting variable name, which will get appended

I have some trouble with my web project.
I'm looking for a solution how I can count my variable upwards in a loop.
So that the name of the variable will go like this: panel1, panel2, panel3...
Thats my code
var panel = []
for(i=1; i<3; i++){
var $div = $('<div class="panel3" id="panel3">Box2 - 20</div>');
$('.panel[i]').append($div);
}
so the "panel[i]" at the bottom should get a higher number for every loop.
I was looking a long time for a solution, but nothing worked.
The idea behind my code is to fill all those empty boxes with a div.
Some HTML
<div class="panel-body">
<!-- Reihe 1 -->
<div class="row">
<div class="col-md-2">
<div class="panel1">
</div>
</div>
<div class="col-md-2">
<div class="panel2">
</div>
</div>
And so on...
Thanks for the help
If your panel name will be panel1, panel2, panel3, so on then you cannot do with this $('.panel[i]'). Instead of that do something like,
for(i=1; i<3; i++){
var div = $('<div class="panel3">Box2 - 20</div>');
var panelClass = '.panel'+i;
$(panelClass).append(div);
}
Hope it helps.
All you need to do is String concatenation with the value of i
var $div = $('<div class="panel3" id="panel'+i+'">Box2 - 20</div>');
And also in the below you doesn't need an array. Just use the parent container identity
$(parentSelector).append($div);
In case if you need all the html in an array
panel[i] = $div;

how to put element into <div> by innerHTML or other ways?

This is my code:
var turn = 1;
var boardPiece;
var piece = [];
function init() {
boardPiece = document.getElementById("pages");
while (boardPiece.firstElementChild) {
if (typeof boardPiece.firstElementChild.id != 'undefined') {
piece.push(boardPiece.firstElementChild);
}
boardPiece.removeChild(boardPiece.firstElementChild);
}
document.getElementById("content").innerHTML = piece[0]; //My problem is here
}
init();
<div id="content">
</div>
<div id="pages">
<div id="page1" class="page">
...
</div>
<div id="page2" class="page">
...
</div>
</div>
The result is a text
[object HTMLDivElement]
not an element.
What's wrong with my .innerHTML? And what is typeof piece[0]? Is it text?
You need to replace your:
document.getElementById("content").innerHTML = piece[0];
with:
document.getElementById("content").innerHTML = piece[0].innerHTML;
What you are trying to do atm is to insert element (which is an object) as a plain text.
You need to use the .innerHTML along with your piece[0] variable like,
document.getElementById("content").innerHTML = piece[0].innerHTML;
Working Fiddle: https://jsfiddle.net/gs0yy50t/
Hope this helps!
The issue is that the type of piece[0] is not a string, but a HTML element. For that reason, in order to assign it to the content's innerHTML (which is a string), JavaScript is implicitly calling the piece[0].toString() method.
When calling the toString() method in HTML nodes (like most non-string objects in JavaScript), it returns a string representing the type of the object.
If you need to add the element piece[0] as child of content, then you should do:
document.getElementById("content").innerHTML = piece[0].outerHTML;
However, if what you need is to copy the content of one element into another, you should use the property innerHTML instead:
document.getElementById("content").innerHTML = piece[0].innerHTML;
Basically, both properties are strings with the HTML code of the element but outerHTML includes the element itself in the root.

How to handle spaces in div id in jquery

I am getting id of div from external source and in that spaces also coming in id , how to get the value of id. Here is my div example:
<div id="123456ABC" class="classname" onclick="javascript:AddValue(aa.value,'33',bb.value,'1000')"></div>
<div id="78904 bbc" class="classname1" onclick="javascript:AddValue(aa.value,'55',bb.value,'2000')"></div>
I need to get the class name from the id. Here is what I am doing:
function AddValue(aa, bb) {
var classOfDiv = $('#123456ABC').attr('class');
var classOfDivs = $('#8904 bbc').attr('class');
alert(classOfDiv);
alert(classOfDivs);
}
The first alert is working fine but second is not fetching a value. How can I handle this? All the values are dynamic.
Use $("div[id='78904 bbc']") to access element which has spaces in id, Try:
var classOfDiv = $("div[id='123456ABC']").attr('class');
var classOfDivs = $("div[id='78904 bbc']").attr('class');
alert(classOfDiv);
alert(classOfDivs);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<div id="123456ABC" class="classname" onclick="javascript:AddValue(aa.value,'33',bb.value,'1000')"></div>
<div id="78904 bbc" class="classname1" onclick="javascript:AddValue(aa.value,'55',bb.value,'2000')"></div>

How to make all child elements red

This is the html code:
<div id="sm-responsive-one">
<p> Step one </p>
<div style="">1</div>
<div style="">2</div>
<div style="">3</div>
<div style="">4</div>
</div>
<div id="sm-responsive-two">
<p> Step two </p>
<div style="">5</div>
<div style="">6</div>
<div style="">7</div>
<div style="">8</div>
</div>
Problem: I want to make 1,2,3 and 4 (child element of sm-responsive-one read color using JavaScript and without using any loop. Is it possible?
This is the code I am trying:
<script>
document.getElementById("sm-responsive-one").getElementsByTagName("div").style.color="red";
//document.getElementById("sm-responsive-one").getElementsByTagName("div")[2].style.color="red";
</script>
You need to use a loop, as getElements* return pseudo-arrays.
If you don't want to use the literal loop syntax, you could apply Array.prototype.forEach, but that's still a loop internally.
var children = document.getElementById("sm-responsive-one").getElementsByTagName("div");
Array.prototype.forEach.call(children, function (it) {
it.style.color="red";
});
First add this CSS rule:
.red-children div {color: red}
Then the javascript is:
document.getElementById('sm-responsive-one').className = "red-children"
getElementsByTagName returns HTML elements collection, so you need to iterate over them:
var elements = document.getElementById("sm-responsive-one").getElementsByTagName("div");
for( var i = 0, len = elements.length; i < len; i++ ) {
elements[ i ].style.color = 'red';
}
Try this:
$("#sm-responsive-one > div").css("color","red");
Check this fiddle:
http://jsfiddle.net/v6xxws1z/

Find an element that contains id of selector + text

I'm confused as to how I should go about doing this.
My page is using PHP to take product codes off a database and using them to generate ids for elements. For example: $("#touch-'.$productcode.'") and $("#popup-'.$productcode.'")
I need to make it so when an element is clicked on, jQuery will find an element in the document which contains the last 11 characters of the selector's id plus additional text.
e.g. the selector $(this) (which has a generated id of #touch-123-456-789) would get its own id, remove everything but the last 11 characters (the product code), append popup- to the beginning, and then find the element $("#popup-123-456-789") and perform an action.
How about some thing like this..
<div class='touch' id='touch-123-456-789'> bla bla </div>
on your jquery
$('.touch').click(function(){
var id = $(this).attr('id');
id = id.substring(5);
$('#popup' + id).doSomething();
});
This is your Html
<div class="pop-up" value= "123-456-789">one</div>
<div class="pop-up" value="123-123-123">two</div>
This is your jQuery
$(".pop-up").click(function(){
var value = $(this).attr("value");
var yourElement = "popup-"+value;
$("#"+yourElement).doSomething(function () {
});
});
Try to break your id like:
$('.touch').click(function () {
var id = $(this).attr('id');
id = id.split(/-(.+)?/)[1];
$('#popup-' + id).html("Hello changed");
});
The .split() here will split the on the first occurrence of "-". So you can do anything with this.
Lets suppose you have two elements in your html code:
<div class='touch' id='touch-123-456-789'> Touch me </div>
<div class="popup" id="popup-123-456-789"></div>
This might help. http://jsfiddle.net/79yut/
HTML:
<div class="element" id="#touch-123-456-790">Sample element1</div>
<div class="element" id="#touch-123-456-791">Sample element2</div>
<div class="element" id="#touch-123-456-792">Sample element3</div>
<div class="element" id="#touch-123-456-793">Sample element4</div>
<div class="element" id="#touch-123-456-794">Sample element5</div>
JS:
for (i = 0; i <= $(".element").length; i++) {
if (i < $(".element").length) {
var id = $(".element").eq(i).attr("id");
id = "popup-" + id.substring(7);
$(".element").eq(i).attr("id", id);
} else {
$("#popup-123-456-792").css('color','blue');
}
}

Categories

Resources