Extract text from a div class with JQuery - javascript

I have this simple HTML code:
<!doctype html>
<html>
<head>
<meta charset="utf-8" />
<title>Demo</title>
</head>
<body>
<script src="jquery.js"></script>
<script src="prova.js"></script>
<div class="altro"><a href=#>Div 1</a></div>
<div class="ann"><a href=#>Div 2</a></div>
<div class="ann"><a href=#>Div 3</a></div>
</body>
</html>
I would like to extract the content of the second div "Div 2" of the class "ann" using a JQuery script. I tried with:
var str = $( ".ann" ).text();
But it takes both Div 2 and Div 3. How can I extract only the one I want?

use .eq() - it takes 0 based index
var str = $( ".ann" ).eq(1).text();
or :eq()
var str = $( ".ann:eq(1)" ).text();

If you want the text from the first div with class "ann":
var str = $('.ann:first').text();
Or:
var str = $('.ann').eq(0).text();
But if you want the text inside the <a> element that is inside the first div with class "ann":
var str = $('.ann:first').children('a').text();
Or:
var str = $('.ann').eq(0).children('a').text();
Note:
- The :first selector limits the selector to the first matching element.
- The .eq() function reduces the matching set to the element with the given zero-based index.

You can try :not(:first):
var str = $(".ann:not(:first)").text();
or
var str = $(".ann").not(':first').text();
fiddle

Related

adding a p tag to the footer using JavaScript

The code should enter "new text" after the Footer text but I'm having issues loading the function.
function insertParagraph(){
var newElement = document.createElement("p");
var node = document.createTextNode("new text");
newElement.appendChild(node);
var element = document.getElementsByTagName("footer");
element.appendChild(newElement);
}
<!DOCTYPE html>
<html>
<body>
<footer>
<P>Footer</P>
</footer>
<script src="main.js"></script>
</body>
</html>
The problem is that getElementsByTagName() returns a collection of elements and collections don't have an .appendChild method. You have to append on to a single element.
Also, you need to call your function so it can run.
function insertParagraph(){
var newElement = document.createElement("p");
newElement.textContent = "new text"; // No need for an explicit text node, just set the text directly
// querySelector() finds the first element that matches the selector argument
document.querySelector("footer").appendChild(newElement);
}
insertParagraph(); // You must call a function so it can run.
<!DOCTYPE html>
<html>
<body>
<footer>
<P>Footer</P>
</footer>
<script src="main.js"></script>
</body>
</html>
function insertParagraph(){
var newElement = document.createElement("p");
var node = document.createTextNode("new text");
newElement.appendChild(node);
var element = document.getElementByTagName("footer");
element.appendChild(newElement);
}
insertParagraph();

How to reduce javascript code that use JQuery and .each()

I have tried to reduce following code
var wgDialog
= jQuery(".ui-dialog.ui-overlay-visible",window.parent.document)
.each
(function(nIndex)
{
var sWidgetName = $(this).attr('data-widgetvar');
var wgDialog = window.parent.PF(sWidgetName);
});
to this code
var jqDialog
= jQuery(".ui-dialog.ui-overlay-visible",window.parent.document)
.children(":first-child");
var sWidgetName = jqDialog.attr('data-widgetvar');
var wgDialog = window.parent.PF(sWidgetName);
but this doesn't work !
The sWidgetName variable is always undefined in last code.
What is my mistake ?
With help of comments, I have found a solution.
I must use get(0) to obtain first element in list returner by JQuery().
And I must use $(jqDialog) instead of jqDialog to get 'data-widgetvar' attribute.
Here is my new code
var jqDialog
= jQuery(".ui-dialog.ui-overlay-visible",window.parent.document)
.get(0);
var sWidgetName = $(jqDialog).attr('data-widgetvar');
var wgDialog = window.parent.PF(sWidgetName);
Assuming you want to access an element with attribute data-widgetvar nested in an element having css classes ui-dialog and ui-overlay-visible you could do the following with plain javascript:
var myElement = document.querySelector('.ui-dialog.ui-overlay-visible [data-widgetvar]');
querySelector allows a CSS like selector combining class together with attribute selector.
Update:
Here is a working example:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title>Test</title>
<script type="text/javascript">
function main() {
var myElement = document.querySelector('.ui-dialog.ui-overlay-visible [data-widgetvar]');
console.log("Attribute value", myElement.getAttribute('data-widgetvar'));
}
document.addEventListener("DOMContentLoaded", main);
</script>
</head>
<body>
<div class="ui-dialog ui-overlay-visible">
<div>some element</div>
<div data-widgetvar="someValue">some text content</div>
</div>
</body>
</html>

Javascript display all (elements, tags) from method elementsbyTagName

Im learning JavaScript and i have problem with DOM methods.
HTML
<html>
<head>
<title>TODO supply a title</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<script src="DOM_Ponovno.js"></script>
</head>
<body>
<div>
<p id="demo" >
this is the first paragraph</p>
<p> boooooooooooommmmmmmmmmmm</p>
<p> third paragraph </p>
<button onclick="changeText()">click me</button>
</div>
</body>
function changeText() {
var tmpTag = document.getElementsByTagName("p");
for(var i = 0;i< tmpTag.length;i++) {
document.write(tmpTag[i].textContent);
}
}
If i follow the tutorial its ok, but i wanted to display all elements by tag name p. I want to display all paragraphs stored in tmpTag.
Someone please explain:
How can ( why cant) display all elements with tag name p ?
How can (why cant) display 3x p tag from variable tmpTag ?
Tried to change to Array with prototype.slice.call method but no success.
You know like Java stuff loop through display/change at index etc..
Thank you :)
Hi and thanx for fast answers.. Sory about the function name it was for testing... I just want to display all elements by tag name p. This code displays only first element and i counter in for loop stops at 1. Why cant i get other 2 paragraph elements ?
Im using document.write like system.out.print in Java to see whats in array. I know if i wanna change i need innerHTML.
If you are wanting to update each paragraph, do not use document write. Try the following:
function changeText() {
var tmpTag = document.getElementsByTagName("p");
for(var i = 0;i< tmpTag.length;i++) {
tmpTag[i].innerHTML = "Your new updated text to change it to for tag index " + i + "...";
}
}
As #Juhana mentioned, the moment you start your loop you overwrite the document using document.write, so all your p tags get removed from the document and replaced by the text in the first paragraph and then your function fails, as the now-empty objects don't have any textContent property. You could concatenate all the contents and write it once:
function changeText() {
var tmpTag = document.getElementsByTagName("p");
var print = '';
for(var i = 0;i< tmpTag.length;i++) {
print += tmpTag[i].textContent;
}
document.write(print)
}
But actually, just don't use document.write - SO snippets don't even allow it anymore! Here a way with a div as output:
var output = document.getElementById('output');
function changeText() {
var tmpTag = document.getElementsByTagName("p");
for(var i = 0;i< tmpTag.length;i++) {
output.textContent += tmpTag[i].textContent;
}
}
<div>
<p id="demo" >this is the first paragraph</p>
<p> boooooooooooommmmmmmmmmmm</p>
<p> third paragraph </p>
<button onclick="changeText()">click me</button>
</div>
<div id="output"></div>
I'm not sure what you're trying to do but you can add another div for result with id='result' and append result you want to it, check following example.
Hope this will help.
function changeText() {
var tmpTag = document.getElementsByTagName("p");
var result = document.getElementById('result');
for(var i = 0;i< tmpTag.length;i++) {
result.innerHTML += tmpTag[i].textContent+'<br>';
}
}
<div>
<p id="demo" >
this is the first paragraph</p>
<p> boooooooooooommmmmmmmmmmm</p>
<p> third paragraph </p>
<button onclick="changeText()">click me</button>
<br>
<div id="result" ></div>
</div>

manipulating tag using java script

I am fairy new in learning JavaScript , I am practising to manipulate a tag,
here is my code
I know that I am making a silly mistake here but I am not sure which part has went wrong ?
could any one please give me some hint ?
<html lang='en'>
<head>
<meta charset="UTF-8" />
<title>
HTML Hyperlinks
</title>
</head>
<body>
<h1>
HTML Hyperlinks
</h1>
<p>
Here is a link to <a name = "hyper" href="http://yahoo.com/">page</a>.
The text around the link is not part of the link.
</p>
<script>
var element = document.getElementsByTagName("a");
var attribute = element.getAttribute("href");
element.setAttribute("href","Http://google.com");
element.setAttribute("target","_blank");
</script>
</body>
</html>
getElementsByTagName says elements. Plural.
It returns a NodeList, which is like an Array, not a single Element.
You need to loop over its return value (e.g. with for) or access it by index ([0])
You are requesting a collection of a tags, but then treating them like a single entity.
<script>
var element = document.getElementsByTagName("a");
var attribute = element.getAttribute("href");
element.setAttribute("href","Http://google.com");
element.setAttribute("target","_blank");
</script>
try this
<script>
var element = document.getElementsByTagName("a")[0];
var attribute = element.getAttribute("href");
element.setAttribute("href","Http://google.com");
element.setAttribute("target","_blank");
</script>
or
<script>
var elements = document.getElementsByTagName("a");
for(var i = 0; i < elements.length; i++)
{
var element = elemenets[i];
var attribute = element.getAttribute("href");
element.setAttribute("href","Http://google.com");
element.setAttribute("target","_blank");
}
</script>
Change this line
var attribute = element.getAttribute("href");
to this
var attribute = element[0].getAttribute("href");

Javascript Special Character removal not working

i have written a jsp code with values coming from other jsp and i need to remove the special characters in the string.But iam not able to remove special characters. Please help
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>JSP Page</title>
<script>
function change(chars){
var dchars=document.getElementById("chars").value;
dchars = dchars.replaceAll("!##$%^&*()+=[]\\\';,/{}|\":<>?", '');
document.getElementById("chars").innerHTML=dchars;
}
</script>
</head>
<%
String res=request.getParameter("tes");
%>
<body onload="change(chars)" ><script>
change(res)
</script>
<div id="chars"> <%=res%></div>
</body>
</html>
There is no "value" for div elements. You need to use innerHtml insted:
document.getElementById('chars').innerHTML = dchars;
try this....
document.getElementById('chars').innerHTML = dchars; //div has no value..
Assuming by special characters, you mean anything that's not letter, here is a solution:
alert(dchars.replace(/[^a-zA-Z ]/g, ""));
OR
alert(dchars.replace(/[^a-z0-9\s]/gi, '')); //will filter the string down to just alphanumeric values
The problem with using innerHTML is that certain characters are automatically converted to HTML entities such as & which is converted to &
function cleanCharsText(){
var el = document.getElementById("chars");
var txt = el.innerText || el.textContent;
el.innerHTML = txt.replace( /[!##$%^&*()+=\\[\]\';,/{}\|\":<>\?]/gi, '');
}
However if you have the following <span> text </span> inside your chars element the html span tags will be removed when you run the above function as we are only extracting the text.

Categories