i am writing some code which need to access a div which contains the particular text
following is the small portion of code i am working on:
var txtElem = txtdiv.getElementsByTagName("div");
txtElem[9].style.border = "2px solid blue";
as seen above i am accessing particular div with the index number, but now i want to add more code which can return me index of div from txtElem which contains the selected text from page
You need to loop trough the divs and check the contents with innerHTML
Try the code below
var txtElem = txtdiv.getElementsByTagName("div");
for ( var i = 0; i < txtElem.length; i++) {
if(txtElem[i].innerHTML === "The text in the div") {
//i is the index of the div that contains the text you searched on
alert(i);
}
}
Loop through divs and use JQuery .html() to check the html content of the div element.
For ease of use you may want to use jquery see http://api.jquery.com/contains-selector/
Related
how can i convert this jquery code to vanilla Javascript
$("h2:contains('" + search + "')").closest(".element").show();
$("h2:not(:contains('" + search + "'))").closest(".element").hide();
i got the second half of the line to be
closest(".element").style.display = "block"
but i cant find a way for the first half to work in normal Javascript. I am creating a live search function to match the text in the search input to match the h2. if they match it will display the content if not the content will display as none.
In Jquery contains gives you a string of text to look for.
So here you need to get all the h2 tag and search in their text.
As h2 elements don't have a value, you should use innerHTML and then instead of contains, you should use includes method.
var allHTwos= document.getElementsByTagName('h2');
for (i=0; i<allHTwos.length; i++) {
var gh = allHTwos[i];
var ts = gh.innerHTML;
if(ts.includes(search)){
// Do your hide/unhide here
}
}
Hi I need to edit some links on a page. Using the below code works but causes other problems on the page. I need the code to only affect elements with a certain input id. I also can't just replace the links as a query will be dynamically added to the end of each link. So in summary i just need to replace parts of all links with an input id "btnViewDetails". Any help would be great I'm very stuck. Cheers
<script language="javascript">
document.body.innerHTML = document.body.innerHTML.replace(/JobSeekers/g,'mobile');
document.body.innerHTML = document.body.innerHTML.replace(/JobPositionDetail.aspx/g,'JobPositionDetail_Mobile.aspx');
</script>
var someVariable = document.getElementsByClassName('btnViewDetails');
(you should use class instead of ID, if it is not a unique value).
someVariable is now an array holding all elements with class name btnViewDetails.
Now replace the text you want to replace only on the href values of you elements (you will have to loop over them):
for (i = 0; i < someVariable.length; i++) {
someVariable[i].href // do your replaces here
}
Is there a way to hide all hashtags on the page with javascript?
For instance, I have a tag cloud underneath each post on a website I'm making. Each tag looks something like: #myhashtag
I want javascript (possibly css?) to run through the document and hide the "#" so that the tag ends up simply looking like: myhashtag
is this possible?
Let the hash tags be elements with a specific class. (Just edit the CSS selector accordingly if you have other identification marks.) Than 8 lines jQuery should do the trick:
$('.my-hash-tag').each(function(i, elem) {
var $elem = $(elem), text = $elem.text();
if(text.length > 0 && text.charAt(0) == '#') {
$elem.text(text.substring(1));
}
});
This will do the job, comments explain how it works. Currently it assumes the tags are inside anchors and inside a div with id #cloud however this is easily edited, just use a different element selector the concept remains the same.
var tagCloud = document.getElementById("cloud"); // Get tag cloud element
var tags = tagCloud.getElementsByTagName('a'); // Find all anchors within cloud (If they aren't anchors change this to containing elements or replace with a class search .etc
for (var i=0, max=tags.length; i < max; i++) { // Loop through tags
tags[i].innerHTML = tags[i].innerHTML.replace("#", ""); // Remove #'s
}
Working fiddle: http://jsfiddle.net/3ayhA/1/
var doc = document.body;
doc.innerHTML = doc.innerHTML.replace(/(\B)#(\w+)\b/g, '$2');
I am wondering if it is possible to remove a tag but leave the content in tact? For example, is it possible to remove the SPAN tag but leave SPAN's content there?
<p>The weather is sure <span>sunny</span> today</p> //original
<p>The weather is sure sunny today</p> //turn it into this
I have tried using this method of using replaceWith(), but it it turned the HTML into
<p>
"The weather is sure "
"sunny"
" today"
</p>
EDIT : After testing all of your answers, I realized that my code is at fault. The reason why I keep getting three split text nodes is due to the insertion of the SPAN tag. I'll create another question to try to fix my problem.
<p>The weather is sure <span>sunny</span> today</p>;
var span=document.getElementsByTagName('span')[0]; // get the span
var pa=span.parentNode;
while(span.firstChild) pa.insertBefore(span.firstChild, span);
pa.removeChild(span);
jQuery has easier ways:
var spans = $('span');
spans.contents().unwrap();
With different selector methods, it is possible to remove deeply nested spans or just direct children spans of an element.
There are several ways to do it. Jquery is the most easy way:
//grab and store inner span html
var content = $('p span').html;
//"Re"set inner p html
$('p').html(content);
Javascript can do the same using element.replace. (I don't remember the regex to do the replace in one stroke, but this is the easy way)
paragraphElement.replace("<span>", "");
paragraphElement.replace("</span>", "");
It's just three text nodes instead of one. It doesn't make a visible difference does it?
If it's a problem, use the DOM normalize method to combine them:
$(...)[0].normalize();
$(function(){
var newLbl=$("p").clone().find("span").remove().end().html();
alert(newLbl);
});
Example : http://jsfiddle.net/7gWdM/6/
If you're not looking for a jQuery solution, here something that's a little more lightweight and focused on your scenario.
I created a function called getText() and I used it recursively. In short, you can get the child nodes of your p element and retrieve all the text nodes within that p node.
Just about everything in the DOM is a node of some sort. Looking up at the following links I found that text nodes have a numerical nodeType value of 3, and when you identify where your text nodes are, you get their nodeValueand return it to be concatenated to the entire, non-text-node-free value.
https://developer.mozilla.org/en/nodeType
https://developer.mozilla.org/En/DOM/Node.nodeValue
var para = document.getElementById('p1') // get your paragraphe
var texttext = getText(para); // pass the paragraph to the function
para.innerHTML = texttext // set the paragraph with the new text
function getText(pNode) {
if (pNode.nodeType == 3) return pNode.nodeValue;
var pNodes = pNode.childNodes // get the child nodes of the passed element
var nLen = pNodes.length // count how many there are
var text = "";
for (var idx=0; idx < nLen; idx++) { // loop through the child nodes
if (pNodes[idx].nodeType != 3 ) { // if the child not isn't a text node
text += getText(pNodes[idx]); // pass it to the function again and
// concatenate it's value to your text string
} else {
text += pNodes[idx].nodeValue // otherwise concatenate the value of the text
// to the entire text
}
}
return text
}
I haven't tested this for all scenarios, but it will do for what you're doing at the moment. It's a little more complex than a replace string since you're looking for the text node and not hardcoding to remove specific tags.
Good Luck.
If someone is still looking for that, the complete solution that has worked for me is:
Assuming we have:
<p>hello this is the <span class="highlight">text to unwrap</span></p>
the js is:
// get the parent
var parentElem = $(".highlight").parent();
// replacing with the same contents
$(".highlight").replaceWith(
function() {
return $(this).contents();
}
);
// normalize parent to strip extra text nodes
parentElem.each(function(element,index){
$(this)[0].normalize();
});
If it’s the only child span inside the parent, you could do something like this:
HTML:
<p class="parent">The weather is sure <span>sunny</span> today</p>;
JavaScript:
parent = document.querySelector('.parent');
parent.innerHTML = parent.innerText;
So just replace the HTML of the element with its text.
You can remove the span element and keep the HTML content or internal text intact. With jQuery’s unwrap() method.
<html>
<head>
<script src="https://code.jquery.com/jquery-1.12.4.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$("button").click(function(){
$("p").find("span").contents().unwrap();
});
});
</script>
</head>
<body>
<p>The weather is sure <span style="background-color:blue">sunny</span> today</p>
<button type="button">Remove span</button>
</body>
</html>
You can see an example here: How to remove a tag without deleting its content with jQuery
How to use an hidden character in text string using JavaScript.There is one text string which i read and writes back with the hidden character in it (so rewritten text looks same as the original text though it comtains the hidden character), so that next time i read the text i can come to know that this text is aleady read as it contains the hidden character
Eg)
< html>
< body>
< div>
This is a simple text
< /div>
< /body>
< /html>
I am trying to parse the div and extract the contents of the div, and insert an hidden character to the text and rewrite the text to the div again using JavaScript.
I just want to know which hidden character should i use to insert into the text ?
How to write the hidden character into the text ?
Since you are using javascript why don't you just add a property to the div:-
var divs = document.getElementByTagName("div");
for (var i = 0, length = divs.length; i < length; i++)
{
if (!divs[i].hasBeenRead)
{
fnReadDiv(divs[i]);
divs[i].hasBeenRead = true;
}
}
To answer the question, keep an array of the divs that have been traversed:
var divsChecked = [];
//code that looks at the div
divsChecked.push(div.getAttribute('id'));
However I think that the method that you are using to traverse the items may not be correct with libraries like jQuery you could loop over each div in turn thereby you shouldn't ever see the same div twice unless you run the loop twice.