I have the following page code:
<html>
<body>
<div id="AAA"> SOME CODE </div>
<div>
<iframe>
<html>
<div id="AAA"> SOME CODE </div>
<div id="myDiv"> MORE CODE </div>
</html>
</iframe>
<iframe>
<html>
<div id="AAA"> SOME CODE </div>
<div id="myDiv2"> MORE CODE </div>
</html>
</iframe>
</div>
</body>
</html>
Now, the fun part.
I can put my hands on the div "myDiv". Then I want to modify the content of div "AAA", the one that is in the same iframe.
However if I do
myDiv.ownerDocument.getElementById("AAA")
I get the element outside the iframe - notice there are three elements with id="AAA"...
My question is, given an element, how can I put my hands on its containing iframe, and not on the most top level document?
Any help is appreciated.
Out of my sleeve, try such function:
function GetTopElement(child) {
var parent = child.parentNode;
while (parent) {
var node = parent.nodeName.toLowerCase();
if (node == "body" || node == "html")
break;
parent = parent.parentNode;
}
return parent;
}
//usage:
var topLevel = GetTopElement(myDiv);
topLevel.getElementById("AAA")...
Use jQuery: $('iframe').contents().find('#123')
Can you not use the following?
first_iframe = document.getElementsByTagName('iframe')[0];
first_iframe.contentWindow.document.getElementById('123')
Then you can reference sucesive iframes:
first_iframes_child = first_iframe.document.getElementsByTagName('iframe')[0];
...
Though I'd advise to your company to use jQuery/Prototype and not use iframes, it'll probably make your life easier.
Related
I do not have access to jquery. I'm trying to implement an accordion, but the content element is not immediately after the header. It is something similar to the following:
<div class="header">...</div>
<div>
<div class="content">
So I'm adding a function to handle an onclick event on the header, which needs to then obtain the next element in the HTML source code that has the content class. How can I achieve that?
You can achieve this using querySlector on the clicked header node
<div class="header">
<div>
<div class="content">
[].forEach.call(document.querySelectorAll('.header'), function(header) {
header.addEventListener('click', function(e) {
var content = this.querySelector('.content');
// here, "this" is the header div, and "content" is the content div
// do majick accordion things here
});
});
How about using recursive function and nextSibling [get next element (not children)]
<div class="header" onclick="hasClass(this)">...</div>
<div>
<div class="content"></div>
</div>
<script>
function hasClass(e){
if(e.nextSibling.children === undefined || e.nextSibling.children.length == 0){
hasClass(e.nextSibling); //go next till find class
}
else{
if(e.nextSibling.children[0].className == "content"){
console.log(e.nextSibling.innerHTML); //get class content html
}
}
}
</script>
You can get this by
var contentDiv= document.getElementsByClassName("content");
try this document.getElementById(header).getElementsByClassName('content');
I have this code in my HTML:
<!DOCTYPE html>
<head></head>
</body>
<div class="exercise ex1">
<h1>Zadanie 1</h1>
<div>
<h3>Chrome</h3>
<div class="chrome"></div>
Opera
</div>
<div>
<h3>Microsoft Edge</h3>
<div class="edge"></div>
Microsoft Edge
</div>
<div>
<h3>Firefox</h3>
<div class="firefox"></div>
Opera
</div>
</div>
</body>
</html>
and I have no idea, how to get to my a tags, so I could change their inner HTML and hrefs in JavaScript. I'll be very grateful for your help!
You can use document.querySelectorAll("a") and a for loop to iterate all a elements in document.
Note, appear to be missing <html> tag , first body element tag should be <body> , not closing </body> tag
<!DOCTYPE html>
<html>
<head></head>
<body>
<div class="exercise ex1">
<h1>Zadanie 1</h1>
<div>
<h3>Chrome</h3>
<div class="chrome"></div>
Opera
</div>
<div>
<h3>Microsoft Edge</h3>
<div class="edge"></div>
Microsoft Edge
</div>
<div>
<h3>Firefox</h3>
<div class="firefox"></div>
Opera
</div>
</div>
<script>
var a = document.querySelectorAll("a");
for (var i = 0; i < a.length; i++) {
console.log(a[i], a[i].innerHTML, a[i].href)
}
</script>
</body>
</html>
You can use querySelectorAll and iterate over the elements
var anchors = document.querySelectorAll('a');
for ( var i = anchors.length; i--; ) {
anchors[i].innerHTML = 'something else';
anchors[i].href = 'http://someother_url.com';
}
Like this:
document.getElementsByTagName("A")
which returns a collection of elements - more specifically, a NodeList object. This can then be accessed in a similar manner to an array:
var allAs = document.getElementsByTagName("A");
console.log(allAs[0].href); //will print "https://www.google.pl/chrome/browser/desktop/index.html"
If you want to know more about how to use this, read more at https://developer.mozilla.org/en-US/docs/Web/API/Document/getElementsByName
As millerbr pointed out, document.getElementsByTagName("A") will return an array like object. You can then edit the hrefs innerHTML by going document.getElementsByTagName("A")[0].innerHTML = "NotChrome"
Check out this jsFiddle
You can iterate over the links in a document using the document.links collection, which contains all A and MAP elements with an href attribute, e.g.
Array.prototype.forEach.call(document.links, function(link) {
console.log(link.href);
});
Note that A elements without an href aren't links, they're anchors (i.e. they are the target of a link). Using getElementsByTagName('a') will return all A elements, including those that aren't links.
The structure of a webpage is like this :-
<div id='abc'>
<div class='a'>Some contents here </div>
<div class='b'>Some other contents< </div>
</div>
My aim is to add this after the class a in above structure.
<div class='a'>Some other contents here </div>
So that final structure looks like this :-
<div id='abc'>
<div class='a'>Some contents here </div>
<div class='a'>Some other contents here </div>
<div class='b'>Some other contents< </div>
</div>
Can there be a better way to do this using DOM properties. I was thinking of naive way of parsing the content and updating.
Please comment if I am unclear in asking my doubt !
Create the desired element, give it the desired attributes, children, innerHTML, etc, and then append it:
var parent = document.getElementById('abc'),
ele = document.createElement('div');
ele.setAttribute('class', 'a');
ele.innerHTML = "Some other contents here";
parent.appendChild(ele);
Fiddle
You can be lazy and just set the innerHTML of #abc, but in my opinion this method is more flexible.
I think this is what you are looking for http://jsfiddle.net/cExRS/
The code is this one
element = document.getElementById('abc');
element.innerHTML = "<div class='a'>Some other contents here </div>" + element.innerHTML;
You should really try jquery, it makes things a lot easier
Liked pointed out there's answer for prepending, Insert sibling node in JS
and How can I implement prepend and append with regular JavaScript?
<html>
<head>
<script type="text/javascript">
function add(myClass) {
var root = document.getElementById('abc');
var last = null;
for (var i = 0; i < root.childNodes.length; i++) {
var child = root.childNodes[i];
if (!child.className) continue;
var pat = new RegExp(myClass,'g');
var m = pat.exec(child.className);
if (!m) {
if (!last) continue;
var div = document.createElement('div');
div.appendChild(document.createTextNode('After A content'));
root.insertBefore(div, last.nextSibling);
break;
}
last = child;
}
}
</script>
</head>
<body>
<div id='abc'>
<div class='d'>Some contents here </div>
<div class='b'>Some other contents </div>
<div class='a'>Content A</div>
<div class='a'>Content A1</div>
<div class='a'>Content A2</div>
<div class='a'>Content A3</div>
<div class='b'>Some other contents </div>
</div>
Add div
</body>
</html>
This question is a duplicate :s
How can I implement prepend and append with regular JavaScript?
It's called prepending
I have the following HTML code within the body:
<div id="hidden">
</div>
<div id="mainContianer">
<div id="firstChildDiv">
</div>
</div>
I am using the following code to get the child
$("div:first-child").attr('id')
But this returns "hidden" when I want it to return firstChildDiv, I have tried things like...
$("div[mainContainer ] div:first-child").attr('id')
$("div[id=mainContainer ] :first-child").attr('id')
$("#mainContainer :first-child").attr('id')
I know its a simple thing to do, but cant seem to see where I am going wrong...
Thanks
Your last selector
$("#mainContainer :first-child").attr('id')
works fine, if you correct the typo in the HTML (see this fiddle). It says mainContianer instead of mainContainer.
But, anyway, why don't you select simply by the id, if that element has an id?
$( '#firstChildDiv' )
$('#mainContainer > div:first-child').attr('id');
Try this,
$("#mainContianer:first-child").attr("id")
Check there is no space before ':'
Actually, you have a typo there in your html
<div id="mainContianer">
should be
<div id="mainContainer">
Then you can do
$("#mainContainer div:first-child").prop('id')
This uses prop rather than attr, which is slower and old jQuery Syntax
This is working for me....
$(document).ready(function(){
var a =$("#mainContainer div:first-child").attr('id');
alert(a);
});
this all return you first child of parent--in your case replace parent by mainContianer
$('#parent').children(":first")
$('#parent').children(":first-child")
$( $('#parent').children()[0] )
$('#parent').find(":first")
$('#parent').find(":nth-child(1)")
try - Child Selector (“parent > child”)
$("div > div").attr('id')
also try out
$("div div:first-child")
<html>
<head>
<script>
function getDiv(){
alert("answer = "+$('#mainContianer div:first-child').attr('id'));
}
</script>
</head>
<body>
<div id="hidden"></div>
<div id="mainContianer">
<div id="firstChildDiv">
</div>
</div>
<button onclick="getDiv()">click</button>
</body>
<html>
SCRIPT
<script language="JavaScript">
jQuery(document).ready(function($) {
$("#MY_BUTTON").click(function(event) {
$("div#PARENT_DIV").find("#CHILD_DIV").hide();
});
});
</script>
HTML CODE
<div id="PARENT_DIV">
<h1 class="Heading">MY HTML PAGE TEST</h1>
<br />
<div id="CHILD_DIV">THIS IS MY CHILD DIV</div>
</div>
<div class="MY_BUTTONS">
<a class="MySubmitButton" id="MY_BUTTON">
<span>Test it!</span>
</a>
</div>
for now in 2020 with jquery it can be like:
function myClickOnDiv(divPrm) {
let div=$(divPrm);
let targetElement=div.find('#my_id')
}
if say you div looks like this:
<div onclick=myClickOnDiv(this)><label id="my_id"></label></div>
First I want to get the outer div by id, then the inner div by class (dynamically added by jquery mobile ui-collapsible content) and finally append a child text node to it.
<div id="aab" data-role="collapsible" data-content-theme="c">
<h3>Heading</h3>
<div class="ui-collapsible-content">
<div id="coll">
Collapsible Content
</div>
</div>
</div>
<p><button onclick='func()'>Button</button></p>
<script>
function func() {
var section = $("#aab > .ui-collapsible-content");
section.appendChild(document.createTextNode("Hello world!"));
}
</script>
I also tried things out with document.getElementById but somehow it doesn't work.. Thanks in advance!
You have use jquery for selection so you should use it for adding child
function func() {
var section = $("#aab > .ui-collapsible-content");
section.append("Hello world!");
}