How to put a link in a div? - javascript

Suppose I have this HTML:
<article id="1919">
<div class="entry-content clearfix">
<div></div>
<div></div>
</div>
</article>
<article id="1910">
<div class="entry-content clearfix">
<div></div>
<div></div>
</div>
</article>
I need to put a link in div with class "entry-content clearfix" for all articles
So can I do it JavaScript:
//take all div with these class value
var eventi_programma=document.getElementsByClassName('entry-content');
//for to read these elements
for(var i=0;i<eventi_programma.length;i++){
var link="http://www.google.it";//(LINK EXAMPLE);
eventi_programma[i].parentElement.innerHTML=''+eventi_programma[i].outerHTML+'</div>';
}
But my code doesn't work.

(function (){
var eventi_programma=document.getElementsByClassName('entry-content');
//for to read these elements
for(var i=0;i<eventi_programma.length;i++){
var link="http://www.google.it";//(LINK EXAMPLE);
eventi_programma[i].parentElement.innerHTML=' THIS IS A LINK </div>';
}
})();
It didn't work because you are putting eventi_programma[i].outerHTML as text of the link. As your for loop is based on .entry-content class it basicly creates a never ending for loop since you keep creating new divs with that classname. So instead of putting outerHTML put some other text.

I assume your entry-content class has only one in every article tag ! So I retrieve all article and added then replace it.
var eventi_programma = document.getElementsByTagName("article");
//for to read these elements
for(var i=0;i<eventi_programma.length;i++){
var link="http://www.google.it";//(LINK EXAMPLE);
org_html = eventi_programma[i].innerHTML;
new_html = "<a href='"+link+"'>" + org_html + "</a>";
eventi_programma[i].innerHTML = new_html;
}

//take all div with these class value
var eventi_programma = $('div.entry-content');
//for to read these elements
for (var i = 0; i < eventi_programma.length; i++) {
var link = "http://www.google.it";//(LINK EXAMPLE);
var temp = eventi_programma[i];
$(temp).parent('article').html('</div>')
}
try it...

Related

Cant get CSS property from child?

I have this HTML code here :
<div id="ctr" class="faden-slider-container">
<div class="conteneur-image" ></div>
<div class="conteneur-image" ></div>
<div class="conteneur-image" ></div>
</div>
And I am trying to get the CSS property of the second div which class' name is conteneur-image but I get nothing :
app.controller("slideCtrl",function ($scope) {
alert("hello")
var tab = new Array();
var elements = new Array();
for(var i = 0; i<3 ; i++){
elements[i] = document.getElementById("ctr").children[i]
}
var style = window.getComputedStyle(elements[1])
var message = style.getPropertyCSSValue("background").cssText()
alert("CSS Value is : "+message)
})
Couple of issues there.
getPropertyCSSValue is obsolete and may not work in browsers anymore
id is a selector, not a valid css property
Use getPropertyValue instead,
var message = style.getPropertyCSSValue("background");
Demo
var style = window.getComputedStyle(document.getElementById("ctr").children[1])
var message = style.getPropertyValue("background");
console.log("CSS Value is : " + message)
<div id="ctr" class="faden-slider-container">
<div class="conteneur-image"></div>
<div class="conteneur-image"></div>
<div class="conteneur-image"></div>
</div>
Using jquery,you can get your 2nd HTML element this way:
var element = $("#ctr").children().eq(1);
Then if you want to make some transformation, like applying style:
element.css("background-color", "blue")
Here is a snippet:
var element = $("#ctr").children().eq(1);
element.css("background-color", "blue")
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="ctr" class="faden-slider-container">
<div class="conteneur-image" >one</div>
<div class="conteneur-image" >second</div>
<div class="conteneur-image" >third</div>
</div>

how to get elements in an element by attrbutes and update it node with purejs?

i have a html tag like this :
<div data-ctrl="master">
<div data-text="txtName"></div>
</div>
<div data-ctrl="master">
<div ><span data-text="txtName"></span> Wiratama</div>
</div>
and in js code i have :
var txtName = 'Yoza';
i want to insert html to every element in document with attribute data-text="txtName" in element with data-ctrl="master" with pure js.
function updateData(txtName){
var html = '<b>' + txtName + '</b>';
//update data for every element with attribute data-text txtName here
var allElements = document.getElementsByTagName('*');
for (var i = 0, n = allElements.length; i < n; i++) {
if (allElements[i].getAttribute("data-text") !== null) {
if (allElements[i].getAttribute("data-text") === 'txtName') {
console.log(nodeTemplate);
// allElements[i].innerHTML = html;
}
}
}
}
that is my js code i tried to.
Use querySelectorAll to return a list of nodes which match your selection. Then iterate over each of them, setting the innerHTML as you go:
function updateData(txtName){
var nodes = document.querySelectorAll('[data-ctrl="master"] [data-text="txtName"]');
for (i = 0; i < nodes.length; ++i) {
nodes[i].innerHTML = "<b>" + txtName + "</b>";
}
};
updateData("Yoza");
<div data-ctrl="master">
<div data-text="txtName"></div>
</div>
<div data-ctrl="master">
<div ><span data-text="txtName"></span> Wiratama</div>
</div>
On all modern browsers, and also IE8, you have querySelector and querySelectorAll on elements (and also on document), which accept CSS selectors. querySelector returns the first matching element (or null); querySelectorAll returns a list.
So if you have an element and want to find all of the elements within it that have the attribute data-text="txtName", you can do:
var list = theElementYouHave.querySelectorAll('[data-text="txtName"]');
So for example:
// Get some element
var element = document.getElementById("foo");
// Find all elements inside it that have `data-text` (at all)
snippet.log("Descendant elements with a data-text attribute: " +
element.querySelectorAll("[data-text]").length);
// Find the *first* element with `data-text="txtName"` and change its
// text to "Yoza":
var txtNameElement = element.querySelector('[data-text="txtName"]');
if (txtNameElement) {
txtNameElement.innerHTML = "Yoza";
}
<div id="foo">
<div data-ctrl="master">
<div data-text="txtName"></div>
</div>
<div data-ctrl="master">
<div><span data-text="txtName"></span> Wiratama</div>
</div>
</div>
<!-- Script provides the `snippet` object, see http://meta.stackexchange.com/a/242144/134069 -->
<script src="//tjcrowder.github.io/simple-snippets-console/snippet.js"></script>

How could I add the same string on different paragraph multiple time on the same HTML page?

I wish to know the best way to write only once the same thing and repeat inside the same page. For example:
<div>
<p id="description1"></p>
</div>
<div>
<p id="description1"></p>
</div>
--
I wish to write only one time the description1 inside the body. I think this could be achieved using the DOM.
Put the elements in the same class using the class attribute, then get the list of all elements using the getElementsByClassName() DOM function. You can then go over the list using a for loop.
[].forEach.call(document.getElementsByClassName("description"), function(elem) {
elem.innerHTML = "StackOverflow saved my day!";
});
You can even put the text in all elements of the same class using no JavaScript and only CSS by using the content attribute.
First of all, the ID field should be unique per element.
If you give all the tags a class <p class="description"></p> then you can use jQuery to set them all by calling:
$('.description').text('This is the text')
In javascript:
var elements = document.getElementsByClassName("description");
for (var i = 0; i < elements.length; i++) {
elements[i].innerHTML = "This is the text.";
}
Have a look at the solutions proposed here
How to repeat div using jQuery or JavaScript?
this one seems to work pretty well:
html:
<div id="container">data</div>
js:
var container = document.getElementById('container');
function block(mClass, html) {
//extra html you want to store.
return '<div class="' + mClass + '">' + html + '</div>';
}
// code that loops and makes the blocks.
// first part: creates var i
// second: condition, if 'i' is still smaller than three, then loop.
// third part: increment i by 1;
for (var i = 0; i < 3; i++) {
// append the result of function 'block()' to the innerHTML
// of the container.
container.innerHTML += block('block', 'data');
}
JSFIDDLE
Just added with a code by using
getElementsByClassName()
`<html>
<body>
<div class="example">First div element with class="example".</div>
<p class="example">Second paragraph element with class="example".</p>
<p>Click the button to change the text of the first div element with class="example" (index 0).</p>
<button onclick="myFunction()">Try it</button>
<p><strong>Note:</strong> The getElementsByClassName() method is not supported in Internet Explorer 8 and earlier versions.</p>
<script>
function myFunction() {
var x = document.getElementsByClassName("example");
for(var i=0;i< x.length;i++)
x[i].innerHTML = "Hello World!";
}
</script>
</body>
</html>`
If you wish to keep id, change your code like this :
script :
var pcount = 2// # p
var desc = document.getElementById('description1');
for(i=0; i<pcount;i++){
document.getElementById('description' + i).innerHTML = desc;
}
html
<div>
<p id="description1"></p>
</div>
<div>
<p id="description2"></p>
</div>
two elements cannot have same id but can have same class
<head>
<script>
var x = document.getElementsByClassName("description");
for (var i = 0; i < x.length; i++) {
x[i].innerHTML = "This is the text.";
}
</script>
<style>
.description1 { // this will apply the same style to all elements having class as description1
text-align: center;
color: red;
}
</style>
</head>
<body>
<div>
<p class="description1"></p>
</div>
<div>
<p class="description1"></p>
</div>
</body>
See the script tag. this solves your problem

How to get innerHTML of DIV without few inside DIV's?

I have some DIV, what contains HTML with images, styles e.t.c. I want to remove exact div's that contains id = 'quot' or className = 'quote', but i don't understand how i can get not only innerHTML of each tag. For example, < p > and < /p > which don't have innerHTML also should be included in final parsed HTML.
var bodytext = document.getElementById("div_text");
var NewText = "";
if (bodytext.hasChildNodes){
var children = bodytext.childNodes;
for (var i = 0; i < children.length; i++){
if (children[i].id != "quot" && children[i].className != "quote" && children[i].innerText != ""){
NewText = NewText + children[i].innerHTML;
}
}
HTML of source need to be parsed:
<div id="div_text">
<p>
Some Text</p>
<p>
Some Text</p>
<p>
<img alt="" src="localhost/i/1.png" /></p>
<div id="quot" class="quote" />
any text <div>text of inside div</div>
<table><tr><td>there can be table</td></tr></table>
</div>
<p>
</p>
</div>
Desired output:
<p>
Some Text</p>
<p>
Some Text</p>
<p>
<img alt="" src="localhost/i/1.png" /></p>
<p>
</p>
Just grab a reference to the targeted divs and remove them from their respective parents.
Perhaps something a little like this?
EDIT: Added code to perform operation on a clone, rather than the document itself.
div elements don't have .getElementById method, so we search for an element manually.
window.addEventListener('load', myInit, false);
function removeFromDocument()
{
// 1. take car of the element with id='quot'
var tgt = document.getElementById('quot');
var parentNode = tgt.parentNode;
parentNode.removeChild(tgt);
// 2. take care of elements whose class == 'quote'
var tgtList = document.getElementsByClassName('quote');
var i, n = tgtList.length;
for (i=0; i<n; i++)
{
// we really should be checking to ensure that there aren't nested instances of matching divs
// The following would present a problem - <div class='quote'>outer<div class='quote'>inner</div></div>
// since the first iteration of the loop would also remove the second element in the target list,
parentNode = tgtList[i].parentNode;
parentNode.removeChild(tgtList[i]);
}
// 3. remove the containing div
var container = document.getElementById('div_text');
container.outerHTML = container.innerHTML;
}
function cloneAndProcess()
{
var clonedCopy = document.getElementById('div_text').cloneNode(true);
var tgt;// = clonedCopy.getElementById('quot');
var i, n = clonedCopy.childNodes.length;
for (i=0; i<n; i++)
{
if (clonedCopy.childNodes[i].id == 'quot')
{
tgt = clonedCopy.childNodes[i];
var parentNode = tgt.parentNode;
parentNode.removeChild(tgt);
break; // done with for loop - can only have 1 element with any given id
}
}
// 2. take care of elements whose class == 'quote'
var tgtList = clonedCopy.getElementsByClassName('quote');
var i, n = tgtList.length;
for (i=0; i<n; i++)
{
// we really should be checking to ensure that there aren't nested instances of matching divs
// The following would present a problem - <div class='quote'>outer<div class='quote'>inner</div></div>
// since the first iteration of the loop would also remove the second element in the target list,
parentNode = tgtList[i].parentNode;
parentNode.removeChild(tgtList[i]);
}
// 3. remove the containing div
//var container = clonedCopy; //.getElementById('div_text');
//container.outerHTML = container.innerHTML;
console.log(clonedCopy.innerHTML);
}
function myInit()
{
cloneAndProcess();
//removeFromDocument();
}

How to get child element by ID in JavaScript?

I have following html:
<div id="note">
<textarea id="textid" class="textclass">Text</textarea>
</div>
How can I get textarea element? I can't use document.getElementById("textid") for it
I'm doing it like this now:
var note = document.getElementById("note");
var notetext = note.querySelector('#textid');
but it doesn't work in IE(8)
How else I can do it? jQuery is ok
Thanks
If jQuery is okay, you can use find(). It's basically equivalent to the way you are doing it right now.
$('#note').find('#textid');
You can also use jQuery selectors to basically achieve the same thing:
$('#note #textid');
Using these methods to get something that already has an ID is kind of strange, but I'm supplying these assuming it's not really how you plan on using it.
On a side note, you should know ID's should be unique in your webpage. If you plan on having multiple elements with the same "ID" consider using a specific class name.
Update 2020.03.10
It's a breeze to use native JS for this:
document.querySelector('#note #textid');
If you want to first find #note then #textid you have to check the first querySelector result. If it fails to match, chaining is no longer possible :(
var parent = document.querySelector('#note');
var child = parent ? parent.querySelector('#textid') : null;
Here is a pure JavaScript solution (without jQuery)
var _Utils = function ()
{
this.findChildById = function (element, childID, isSearchInnerDescendant) // isSearchInnerDescendant <= true for search in inner childern
{
var retElement = null;
var lstChildren = isSearchInnerDescendant ? Utils.getAllDescendant(element) : element.childNodes;
for (var i = 0; i < lstChildren.length; i++)
{
if (lstChildren[i].id == childID)
{
retElement = lstChildren[i];
break;
}
}
return retElement;
}
this.getAllDescendant = function (element, lstChildrenNodes)
{
lstChildrenNodes = lstChildrenNodes ? lstChildrenNodes : [];
var lstChildren = element.childNodes;
for (var i = 0; i < lstChildren.length; i++)
{
if (lstChildren[i].nodeType == 1) // 1 is 'ELEMENT_NODE'
{
lstChildrenNodes.push(lstChildren[i]);
lstChildrenNodes = Utils.getAllDescendant(lstChildren[i], lstChildrenNodes);
}
}
return lstChildrenNodes;
}
}
var Utils = new _Utils;
Example of use:
var myDiv = document.createElement("div");
myDiv.innerHTML = "<table id='tableToolbar'>" +
"<tr>" +
"<td>" +
"<div id='divIdToSearch'>" +
"</div>" +
"</td>" +
"</tr>" +
"</table>";
var divToSearch = Utils.findChildById(myDiv, "divIdToSearch", true);
(Dwell in atom)
<div id="note">
<textarea id="textid" class="textclass">Text</textarea>
</div>
<script type="text/javascript">
var note = document.getElementById('textid').value;
alert(note);
</script>
Using jQuery
$('#note textarea');
or just
$('#textid');
$(selectedDOM).find();
function looking for all dom objects inside the selected DOM.
i.e.
<div id="mainDiv">
<p>Paragraph 1</p>
<p>Paragraph 2</p>
<div id="innerDiv">
link
<p>Paragraph 3</p>
</div>
</div>
here if you write;
$("#mainDiv").find("p");
you will get tree p elements together. On the other side,
$("#mainDiv").children("p");
Function searching in the just children DOMs of the selected DOM object. So, by this code you will get just paragraph 1 and paragraph 2. It is so beneficial to prevent browser doing unnecessary progress.

Categories

Resources