Reading a value from 'this' instance in jQuery - javascript

When I am printing 'this' instance in alert box, it is printing something like this.
[object Object]
But the actual content in it is
<dl>
<dt>
my Name <span> John Krishna </span>
</dt>
<dd>
<span>My fathers name</span>
</dd>
</dl>
I want to display only 'my Name' instead of [object Object]. I mean what ever content of span in that 'dt' I want to display it in my alert box.
For this I tried out around in google, every where I am getting solutions like use child, or using inner html content and in some solutions someone written for loops. But I don't want to write any for loops around it which makes my code large.
Some one please suggest me some way that how can I print only "my Name" in alert box.

It depends on how you did the selection. If it is on the whole dl tag, than it should be something like this
alert($("dl").find("dt").clone().find("span").remove().end().html());
Where dl is an example selection. I don't know how you get it (by id, class etc.)
if you're selecting dt tag directly, than you should use a shorter version
alert($("dt").clone().find("span").remove().end().html());

It sounds to me like you're trying to alert an entire object. You'll need to make use of jQuery's text() method to display only the element's text.
If this is already selecting the span element you're after, you can simply use:
alert($(this).text()); // Instead of alert($(this));
I need only text inside 'dt' and content inside span should not be printed
For this we can use a regular expression to replace the <span> content from the dt element's HTML:
alert($('dt').html().replace(/<span>.*<\/span>/,''));
Here's a JSFiddle demo of this in use.
This is 96% faster than using cloning the element as some of the other answers below have suggested.

Add an id to the span (e.g. <span id="myname">Test Name</span>) and then match on the id in jQuery (using $("#myname")) and alert the text of that element to return what you need.
For example:
alert($("myname").text());

try to map : collecting them into an array instead of two calls to $:
var texts = $('span').map(function(){
return this.previousSibling.nodeValue
});
texts[0]; // "Some text followed by "
texts[1]; // " and another text followed by "
alert(texts[0]);
Hope it will help

you will need to use:
$(this).html();

try this:
var name=$(this).children('dt').children('span').text();
alert('name --->'+name);
Thanks

Use:
alert($(this).find("dt span").text());
Getting the text outside of the span is a little tricky in jQuery. I found this code here:
var myName = $(this).find("dt")
.clone() //clone the element
.children() //select all the children
.remove() //remove all the children
.end() //again go back to selected element
.text();

Related

How do you move text from a div into an input value?

I am trying to move text from inside a div into the value from an input field but I'm getting [object Object] as the output. Can anyone explain why?
input = $('#input').contents();
$('#output').val(input);
Spencer.
The .contents() method won't give you the text, but an object with a collection of the elements it contains. You sould use:
val method:
The .val() method is primarily used to get the values of form elements
such as input, select and textarea.
text method:
The .text() method cannot be used on form inputs or scripts. To set or
get the text value of input or textarea elements, use the .val()
method.
The line you're looking for is:
$('#input').val($('#div').text());
and can be decomposed like this:
var textToMove = $('#div').text();
$('#input').val(textToMove);
Here is a full example:
function move(){
$('#input').val($('#div').text()); //copy text
$('#div').text(''); //erase text
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id='input' type='text' value=''>
<div id="div">Hello, Spencer</div>
<button onclick='move()'>Click to move text</button>
First get the text content with
$("#d").text()
Add this to input like
$("#y").val($("#d").text());
Now you can remove text of div like
$("#d").text("")
$("#y").val($("#d").text());
$("#d").text("")
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.0/jquery.min.js"></script>
<div id="d">text</div>
<input type="text" id="y"/>
Note:
Given a jQuery object that represents a set of DOM elements, the .contents() method allows to search through the immediate children of these elements in the DOM tree and construct a new jQuery object from the matching elements. and the results includes text nodes and comment nodes as well as HTML elements in the resulting jQuery object. Here
That's why you are getting object. you really need to use .text() here to get the text contents only.
The contents() you were trying to use is defined by the jQuery documentation as
To get the children of each element in the set of matched elements,
including text and comment nodes
So, contents() is returning en entire object with all those children, comments and etc... that's why: [Object Object]. If you use console.log($('#input').contents()) you will be able to see the entire object in the console.
So, in that case, it's better to use text(), that get only the text content of the element matched.
After getting the text, then set it to the input with val();
the example below shows this. (I added a timer just to better represent the code working, you can remove it and let only the code that is inside).
Also, if you want to keep the text in the div, remove the part where I used .text('');
setTimeout(function(){
input = $('#input').text();
$('#output').val(input);
$('#input').text('');
}, 1500);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type='text' value='' id="output">
<div id="input">Abcdef 1234567890</div>

Style a string within a paragraph with an ID

I have this HTML:
<p>
(rcvd)
Title
by Person,
<br></br>
- More text
</p>
And I want to change the color of (rcvd) to green. I tried the following:
This changes the entire line to green but keeps the link
$("p:contains('(rcvd)')").attr("style","color:green");
This changes the rcvd part to green but removes the Title link
$("p").each(function() {
var text = $(this).text();
text = text.replace("(rcvd)", "<span style='color:green;'>(rcvd)</span>");
$(this).html(text);
});
This does nothing, but I think it's the solution I want with a small tweak somewhere that I'm missing
$(p).html($(p).html().replace("(rcvd)","<span style='color:green;'>(rcvd)</span>"));
Any pointers welcome (I am still new to JQuery and trying to learn so I'd love an explanation as to why you make the suggestion you make.
My own suggestion would be:
$('p').html(function(i,h){
return h.replace('(rcvd)', '<span class="greenColoured">(rcvd)</span>');
});
Using CSS to supply the style:
.greenColoured {
color: green;
}
JS Fiddle demo.
As noted by TrueBlueAussie (in comments, below), I've not explained the parameters in the anonymous function passed to the html() method: the function(i, h):
The html() method essentially iterates over the collection returned by the selector (in this case over all the paragraphs selected); without use of the anonymous function each p element would have the same HTML set. Using the function, with the i and v (which can be named however you please allows you to access the index (i) of the currently iterated-over element amongst the collection, and v (the second parameter) returns the current 'value' (in this case the existing innerHTML of the current node being iterated over).
As noted, these parameters can be called anything you like, for me i and h are habitual (i for 'index' and h for HTML in this case); so long as you remember that (as with many other anonymous functions passed to jQuery methods) the first is the index and the second the 'current-value'.
References:
html().
String.replace().
This will select the first node within the P (which happens to be a text node) and style it:
$("p").contents().first().wrap("<span style='color:green'></span>");
Demo: http://jsfiddle.net/jrAWn/
UPDATED. Ok, and this is using class:
.rStyle {
color:green;
}
$("p").contents().first().wrap("<span/>").parent().addClass("rStyle");
Use css() and give your <p> tag a class:
<p id="myGreenClass">(rcvd)</p>
And this jQuery code:
$('.myGreenClass').css('color', 'green');
Try wrapping the tag names in quotes (jsFiddle):
$("p").html($("p").html().replace("(rcvd)","<span style='color:green;'>(rcvd)</span>"));
At the moment you are passing the variable p to the jQuery function. Presumable p is undefined, so you either get a Javascript error or just an empty jQuery object.
As others have said, the standard way to do this is wrapping the rvcd in a span:
<p>
<span class="style-this">(rcvd)</span>
Title
by Person,
<br></br>
- More text
</p>
And
$(".style-this").css("color", "green");

Update text content with minified.js

What is the right way to update text of a element with minifiedjs?
E.g.
<a class="myRef">Old text</a>
I have tried logical:
$('.myRef').text('New text');
But it doesn't work.
http://minifiedjs.com/docs/howto.html#html_text
$('.myRef').fill("My new text");
I get it right from documentation.
You can use the fill method to replace the existing text value.
$('.myRef').fill("New Text Value");
or you can use the add method to append text to the existing text.
$('.myRef').add("Append Text");
(The text method returns the concatenated text content of all nodes in the list.)
This list of How To's is helpful for learning how to use minifiedjs.

How can I replace a tag without disturbing the content?

Am just wanted to remove an html tag (both opening and closing) without disturbing the content.
For example, given this markup...
var temp =
<span id="myspan1">
<span id="myspan2" class="new">
hello world !</span>
</span>
I want to get to this...
var newcontent =
<span id="mySpan1">
hello world !
</span>
Please help me resolve with this in jquery.
I think jQuery's got an unwrap. Since unwrap removes the parent, we need to get the contents of #myspan2 to make #myspan2 the parent to be removed, ending up with #myspan1 being the parent.
$('#myspan2').contents().unwrap();
To further clarify why unwrap is better than doing html is that when you do .html(), it only retrieves a string representation of the DOM descending from the current element. It does not fetch the handlers and data that come with those descendants. Thus, if you recreate the DOM with that HTML string, it does recreate the DOM properly but does not anymore have the handlers and data that were attached to those descendants.
Try below code
$('#myspan1').html($('#myspan2').html())
This should work, as long as you have no other content in the myspan1 span:
$("#myspan1").html($("#myspan2").html());
It replaces the content of the myspan1 span with the contents of myspan2, effectively removing the tag. For the example given it works, but it would fail if you have other content inside myspan1 besides myspan2.
$('#myspan1').html($('#myspan2').html());
Try
var temp = '<span id="myspan1"><span id="myspan2" class="new">hello world !</span></span>';
var $t = $(temp);
$t.find('.new').contents().unwrap();
console.log($t[0].outerHTML)
if you are looking to assign the content of a immediate child element to parent element, you can use this
$("#myspan2").parent().html($("#myspan2").html());

Need jQuery text() function to ignore hidden elements

I have a div set up something like this:
<div id="test"> <p>Hello</p> <p style="display: none">Goodbye</p> </div>
EDIT: To clarify, this is the simplest example. The div could have any arbitrary number of n deep nested children.
$('#test').getText() returns 'Hello Goodbye'. Here's a one liner to test in Firebug: jQuery('<div id="test"> <p>Hello</p> <p style="display: none">Goodbye</p> </div>').text()
This seems to be because what jQuery uses internally, textContent (for non IE), returns hidden elements as part of the text. Hrmph.
Is there a way to return the text content ignoring display:none'd elements? Basically I am trying to mimic the text you would get from highlighting the div with your mouse and copying to system clipboard. That ignores hidden text.
Interestingly, if you create a selection range and get the text from it, that also returns text inside display:none elements.
var range = document.body.createTextRange();
range.moveToElementText($('#test')[0]);
range.select();
console.log(range.toString()); // Also logs Hello Goodbye!
So creating a document selection range doesn't appear to do the same thing as highlighting with the mouse in terms of display:none elements. How do I get around this dirty pickle conundrum?
Edit: using .filter(':visible').text has been suggested, but it won't work for this scenario. I need the returned text to be EXACTLY what would come from a selection with the mouse. So for example:
$('<div>test1 <p>test2</p>\r\n <b>test3</b> <span style="display:none">none</span></div>').appendTo(document.body).children().filter(':visible').text()
returns
"test2test3"
When the output I actually want is
test1 test2
test3
linebreaks, whitespace and all, which come from the \r\n
Filter the elements using .filter(":visible").
Or use this:
$("#test :visible").text();
But the jQuery documentation advises us to use .filter() instead:
Because :visible is a jQuery extension and not part of the CSS specification,
queries using :visible cannot take advantage of the performance boost provided by the native DOM querySelectorAll() method. To achieve the best performance when using :visible to select elements, first select the elements using a pure CSS selector, then use .filter(":visible").
Use :visible in your selector as such:
$("#test > p:visible").text()
A Function example:
-- Edit:
http://jsfiddle.net/8H5ka/ ( Works on Chrome it displays "Hello" in Result )
If the above doesn't work:
http://jsfiddle.net/userdude/8H5ka/1/
If space isn't a major concern you could copy the markup, remove the hidden elements, and output that text.
var x = $('#test').clone();
x.filter(':not(:visible)').remove();
return x.text();
I had this problem and found this question, and it seems the actual solution is based on the provided answers but not actually written out. So here's a complete solution that worked for my situation, which is the same as the OP with the additional provision that elements may be invisible due to external styles based on DOM position. Example:
<style>.invisible-children span { display: none; }</style>
<div class="invisible-children">
<div id="test">Hello <span>Goodbye</span></div>
</div>
The solution is to:
Make a clone of the entire object.
Remove invisible objects in place; if we take #test out of the DOM before we remove invisible objects, jQuery might not know they're invisible because they will no longer match the CSS rules.
Get the text of the object.
Replace the original object with the clone we made.
The code:
var $test = $('#test');
// 1:
var $testclone = $test.clone();
// 2: We assume that $test is :visible and only remove children that are not.
$test.find('*').not(':visible').remove();
// 3:
var text = $test.text();
// 4:
$test.replaceWith($testclone);
// Now return the text...
return text;
// ...or if you're going to keep going and using the $test variable, make sure
// to replace it so whatever you do with it affects the object now in DOM and
// not the original from which we got the text after removing stuff.
$test = $testclone;
$test.css('background', 'grey'); // For example.
Here is how I did it with MooTools:
$extend(Selectors.Pseudo, {
invisible: function() {
if(this.getStyle('visibility') == 'hidden' || this.getStyle('display') == 'none') {
return this;
}
}
});
Element.implement({
getTextLikeTheBrowserWould = function() {
var temp = this.clone();
temp.getElements(':invisible').destroy();
return temp.get('text').replace(/ |&/g, ' ');
}
})
I search for that and found this question but without solution.
Solution for me is just get out of jquery to use DOM:
var $test = $('#test').get(0).innerText
or if more than on element in array of selector, you need a for loop and a merge but I guess that most of time it is the first version that you need.
var $test = $('#test').get().map(a => a.innerText).join(' ');

Categories

Resources