Getting text from a paragraph in jquery - javascript

This might be a very simple thing in jquery but I am not able to figure it out. My html document has the following structure
<div class="body">
<p>This is the text I want to extract</p>
</div>
I tried this
$("body").find("a p").text()
but this does not seem to be working for me. I am able to get the paragraph object but not the text. I tested it with console.log with no use.

What you have should be working (you can test it here), make sure you're running it when the DOM is ready though, like this:
$(function() {
alert($("body").find("a p").text()); //or just $("a p").text()
});
If it runs earlier, the elements may not be ready, and your selector won't find any matches.
If you want to select the class body make sure to use ".body" instead of "body" (which would select the <body> element). Here's a version using the .class selector:
$(function() {
alert($(".body a p").text());
});

the .html() function retrieves a nodes inner html.
$('.body a p').html();
should do the trick

Not sure if this would cause a problem, but you have invalid markup. From "The global structure of an HTML document" by the W3C
Generally, block-level elements may contain inline elements and other block-level elements. Generally, inline elements may contain only data and other inline elements. Inherent in this structural distinction is the idea that block elements create "larger" structures than inline elements.
a elements are supposed to be contained by block elements like p, not the other way around.

here is your paragraph element in html or php file which is id assign tt
<p id="tt">ALert Message </p>
in in jquery file to get the text of your paragraph with tt id can be
var tt = $("#tt").text();
alert(tt);
working fine for jquery-3.1.1.js

Related

Input text in draft.js

I'm doing automation test and I need to input text in a text field, but the problem is there is no 'input' to do this.
This one won't work:
document.querySelector([class*=modal-dialog] [class*=AddCitation_] [class*='DraftEditorPlaceholder']).value='Hello World'
Does any one know how to input text in draft.js?
You can use document.execCommand("insertHTML", "html string here", false)
As you can see draft js uses contenteditable property of div to write text
So if you want to automate tests with draftjs insert any sample html string with command
so you have a sample text in draft editor now you can perform tests
Read this
https://developer.mozilla.org/en-US/docs/Web/API/Document/execCommand
Let's first understand the code you have written:
document.querySelector([class*=modal-dialog] [class*=AddCitation_] [class*='DraftEditorPlaceholder']).value='Hello World'
This code attempts to:
get the first element
which has a class containing 'DraftEditorPlaceholder' and
which has an ancestor having a class containing AddCitation_ which
has an ancestor having a class containing modal-dialog
So, you will first need to ensure that the element you try to edit is inside an element having a class containing modal-dialog. In your screenshot we cannot see such an ancestor element, the root having a class of modal-content. If the selector you have written does not find an element, then an error will be thrown when you try to assign a value to any of its attributes, like value in this case. You have an element having a class of styles_AddCitation__3_D5j, which is the child of the element of the class of modal-content. You have an element having a class of public-DraftEditorPlaceholder-root, which, assuming that you have a class containing the modal-dialog text being its ancestor, then the selector will find it. However, this is the sibling of the element which you seem to expect to find with your query. So, you will need to sort out where you intend to put your text into.
Now, assuming that you have sorted your selector out and there is a span in the element you are talking about, you will need to write span at the end of your selector, with a space before it. Also, in this case you will need to set innerText instead of value to your desired value. If the target element is an input, then setting a value should suffice.
Another possible problem is that your Javascript code might run before the structure is actually generated, hence not being able to set attributes of elements which do not exist yet. So you will also need to make sure that your structure is in place indeed when this Javascript code runs.
const screen = document.getElementById("screen");//get span ID
screen.innerHTML += `<span class="screen" >${
this.textContent
}</span>`);//add text content
<body>
<h1>CALCULATOR</h1>
<!-- <div class="container"> -->
<div class="container">
<div class="column2" id="screen">
<!-- <span class="screen"></span> -->
</div>
I used this to insert span tags into a div tag.
I'm only a beginner so it might not be optimal
I used this while experimenting with JS on a simple calculator, because I wanted to see if it could work without using an input tag.
please let me know if this helps as it will also help me to see if my understanding is good

Find <style> tag by class not working

I'm using AJAX to fetch some HTML markup. I want to append some style tags (with a class) from the fetched markup to my own document using find(). However, jQuery does not seem to like the following approach.
(link removed due to lack of reputation)
Could someone shed some light on why this does not work, and point me in the right direction?
Thank you in advance.
Solutions
Making it a native element first (and removing script tags as extra precaution) works. http://jsfiddle.net/T6QCR/5/
Also, a lot simpler, using innerHTML instead of .html() works, as setting innerHTML does not evaluate scripts and allows .find() to function. http://jsfiddle.net/T6QCR/8/
Also, laconbass' answer below.
Thank you for the help!
Parse the HTML chunk rather than just passing it to jQuery
From the jQuery function documentation for the case you are using:
(...) if the string appears to be an HTML snippet, jQuery attempts to
create new DOM elements as described by the HTML. Then a jQuery object
is created and returned that refers to these elements. You can perform
any of the usual jQuery methods on this object.
(...)
If the HTML is more complex than a single tag without attributes, as
it is in the above example, the actual creation of the elements is
handled by the browser's innerHTML mechanism. In most cases, jQuery
creates a new element and sets the innerHTML property of the
element to the HTML snippet that was passed in.
(...)
When passing in complex HTML, some browsers may not generate a DOM
that exactly replicates the HTML source provided. As mentioned, jQuery
uses the browser"s .innerHTML property to parse the passed HTML and
insert it into the current document. During this process, some
browsers filter out certain elements such as , , or
elements. As a result, the elements inserted may not be
representative of the original string passed.
The documentation recomends ussing $.parseHtml()
For explicit parsing of a string to HTML, use the $.parseHTML()
method.
$.filter rather than $.find
As you noted, $.find does not work on this example. I had succeed replacing it with a $.filter call.
// this works
$html.filter('.test');
// this doesn't works
$html.find('.test');
// better if you filter also by tag
// surely you will have more tags other than <style> on the retrieved html
$html.filter('style.test');
See how this applies to your example on this fiddle.
body is not defined, the console gives an indication of this by way of an error, too. If you want to use jQuery to select the markup body and append the style then you will need to use an appropriate selector:
$("body").append($style);
<style> element can't has class attribute, because Uncaught SyntaxError: Unexpected identifier.
This code shoud work:
var html = '<html><head><style>aaa</style></head></html>';
var $html = $.parseHTML(html);
$.each($html, function(i, el) {
if(el.nodeName == "STYLE") {
$("head").append(el.outerHTML);
return false;
}
});
I'm not really sure as to why this is, but it has something to do with the document model and how it works. You can't just hold a temporary var with the html text in it, you need to put it all inside an element (like a div) that is attached to the document in some way. This div could be hidden from view from the user.
<html>
<head>
<div></div>
</head>
<body>
<script>
jQuery(document).ready(function($) {
$('div').hide().html('<html><head><style class="test"></style></head></html>'); // From AJAX request
var $style = $('div').find('.test');
document.body.appendChild($style[0]);
});
</script>
</body>
</html>

How to get element from template by javascript?

I dont know good method how to get DOM element from template by javascript.
Example template:
<script id = "template" type="text/template">
<div>text1</div>
<div>text2</div>
<div>text3</div>
</script>
For example i want get div with "text2"
There is ways which i know, all of them are bad:
Add "class" to all elements - it breaks semantics (class created for CSS). In big projects you must use very long names for classes, its very inconvenient.
Get element by his number (index) - when adding a new element, you must rewrite old numbers in your code.
I see a couple of options:
If you don't want to use class , you can use a data-* attribute.
Assuming you load the template once and then duplicate its contents as desired, you could put id values on the elements in the template, which you then remove when cloning them and adding them to the document (so you don't end up with the same id on more than one copy of the element, which would be invalid and probably counterproductive).
Maybe you can also create as many templates as you need.
One for each div.
If you need to get each div at a time you must set ids to them ... of course you can also browse the dom inside script element to find the one you're interested in ...
Home this helps
Regards
mimiz

JavaScript String .replace method is replacing all my content?

I have successfully implemented finding and replacing some text with something else in the following way:
$(".class").html($(".class").html().replace(/\text\b/g, '<span class="newclass newclass2">new text</span>'));
When I apply this to my element 'class' it finds all the 'text' and replaces with 'new text' and everything relating to the new classes.
However, if I have more than one element on the page with the same class, it replaces all the classes with whatever text is in the first class.
For example, if my first class has the content "Hello everyone", when the script is applied to this class, it works fine. Any subsequent class of the same name is then replaced with "Hello everyone". These also have the function applied in the same way as the first occurrence of that class.
IE, it applies the script, then replicates this in every single class of the same name on the page.
I do not understand why it would do this, and rather renders the function pointless in many ways if it can't be used to change text throughout different sections without setting up new scripts and different classes.
Hopefully there is something simple at work here that I am not aware of, any help would be much appreciated.
Many thanks
Richard
That is the nature of class selectors--the .html(...) will replace the HTML of everything that matches the .class selector.
If you want to replace text in each individual .class element, you can use the .each function. (There are probably jQuerier ways, too.)
$(`.class`).each(function(n, el) {
var myHtml = $(this).html();
myHtml = mungeIt(myHtml);
$(this).html(myHtml);
});
If you want to select only an individual .class element, then you either (a) don't really want to be using classes, but IDs, or (b) need to understand enough of your structure or the context you wish to operate in to select only the targeted DOM element.
(And hope the structure or context doesn't change without a corresponding code update.)
You're specifying a class with the jQuery selector $(".class") That's what the period indicates. jQuery has a ton of selectors to choose from. A list is provided in the documentation here: http://api.jquery.com/category/selectors/
Also, I'd look at http://api.jquery.com/hasClass/ for your problem as you could then use if...then statements to not run into others
Dave is right about needing to use the .each method. We need to loop through each element at a time because .html() will only return the first element when there are multiple matches.
Try:
$('.class').each(function() {
$(this).html($(this).html().replace(/someWord/g,'withAnother'));
});

Prototype.js get text from an element

I'm new to Protoype.JS and just testing it a bit because I heard it was good, but I'm stuck quite quickly.
As easy as this is with jQuery, it seems to be the end of the world to get the text in an element. I've tried innerHTML in multiple ways but the only thing I can get is "undefined".
alert($$('.mnu_item').innerHTML);
alert($('content').innerHTML);
None of these work.
Content is a div with id "content" and .mnu_item is an anchor tag with class ".mnu_item".
I don't get what the problem is, probably something stupid but it would be great if somebody could point me in the right direction!
EDIT: I've found that it isn't the innerHTML that doesn't work but it's the class selector. The second line in the code above does work. How can I select an element by its class in the latest Prototype version if this isn't the correct way?
Has the DOM loaded when you run your script? If you're not running this code in a window.onload or by placing it at the end of the body, then the elements by not exist when it runs.
Try placing your script just inside the closing </body> tag.
<body>
<!-- my content -->
<script type="text/javascript">
alert($('content').innerHTML);
</script>
</body>
Also, your first line is selecting correctly, but will return an Array of elements, so innerHTML will be undefined.
To iterate the Array, you can do this:
$$('.mnu_item').each(function(val,i) {
alert(val.innerHTML);
});
or if you want to end up with an Array of the innerHTML values, do this:
var values = $$('.mnu_item').map(function(val,i) {
return val.innerHTML;
});
Make sure the DOM is loaded before you run these tests:
$(document).on('dom:loaded', function () {
/* code to execute after dom has loaded */
})
The first line of code $$('.mne_item') doesn't work because $$ gives back an array of all elements matching the css rule. So $$('.mne_item') gives an array of all dom elements which has the class mne_item. You can ask the first one by using the first method or iterate over all items like this:
$$('.mne_item').each(function(elem) {
// elem is the li elements extended by all Element methods of prototype
});
If you use $ in jQuery, it actually uses a similar pattern but hides the each construct. It just applies the chained method to all elements or just the first.
The second line of code $('content').innerHTML should work. $ is a shortcut for document.getElementById so it should give you a DOM node back. The reason why this doesn't work is there is no node where id = content, probably because the dom isn't loaded yet.
For more info about the methods of prototype look at the api: http://api.prototypejs.org/
Also check the default DOM methods: http://quirksmode.org/dom/w3c_core.html
$('content').innerHTML should work. Check your HTML, ensure the ID is unique.
var text = $$('label[for="display_on_amazon"]').first().textContent;
Above code worked for me.
Regarding, $$('.mnu_item').innerHTML
When you are trying to fetch with class selector, prototype returns array of multiple elments, by using [0] or first() method system will point at the first element in that array, after that you can use innerHtml (to get html inside the element) or textContent (to get text content of that element, native javascript method)

Categories