Issue with the contains method and highlighting elements - javascript

I want to highlight an element that contains a string written in a textbox. This is the part of the code that's supposed to do it:
$("#rightContainer .magnifier").click(function () {
var a = $("#searchBox").val();
if (a != "") {
var foundin = $('div:contains(a)');
foundin.addClass("highlighted");
alert(a);
}
})
The problem is that the whole page gets highlighted. I'm assuming this happens because I have a main container which has its children containers, so the contains method selects the whole main container. Is this the case or is it because of something else, and does anyone have a better way of doing this? Thanks in advance.

The :contains selector will return any element which contains the text you're searching for, in this case "a". This has nothing to do with the variable named a. Perhaps you meant to do something like this:
$("#rightContainer .magnifier").click(function () {
var a = $("#searchBox").val();
if (a != "")
{
var foundin = $("div:contains('" + a + "')");
foundin.addClass("highlighted");
alert(a);
}
})

If I understand correctly, you only want the div highlighted which is wrapping that searchbox and not any other div. Use closest() to find that div.
$("#rightContainer .magnifier").click(function () {
var a = $("#searchBox").val();
if (a != "")
{
$("#searchBox").closest('div').addClass('highlighted');
}
})

Related

JS complex operation of the selected text

Great minds JavaScript, please help.
I need to deal with the complex operation of the selected text.
I have some text with a lot of html tags, and I need to get a function that returns the following result:
The user selects text in a particular tag with the class, for example <div class="text">,
and the function is activated in the event that:
$('.text').mouseup(function (e){...});
returns the beginning of the selection
returns the end of the
selection identifies a particular tag, with his class
Moreover:
the number of characters to be given html tags,
but you can exclude
some tags example ,
Ok, some code, what I have:
$(function () {
$('.text').mouseup(function (e){
$(this).highlight(getSelectionText());
})
})
this demo
Here we highlight the desired part of the text, but did not return the
correct position
In addition, the text is released coincidentally
characters, and I need it for the position
You might want to try this:
$(function () {
$('#detailBoxParagraph').mouseup(function (e){
var selectedText = getSelectionText();
$(this).removeHighlight();
$(this).highlight(selectedText);
var txt = $(this).text();
var pos = [];
var i = txt.indexOf(selectedText);
if(i > -1) {
pos.push({"start": i+1, "end": i + selectedText.length});
}
while (i != -1) {
i = txt.indexOf(selectedText, i + 1);
if(i > -1) {
pos.push({"start": i+1, "end": i + selectedText.length});
}
}
console.log(pos);
})
//alertSelection();
})

How do you target THIS Parent, from a child to make another child div show using nothing but classes with pure javascript?

So I have a bunch of data thats being loaded in dynamically so I have to use classes to pull this off.
Just using pure javascript and not jquery, how do I make it so that when you click view more in a div, it makes the hidden div only show from THIS parent?
Structurally, you have a couple choices.
When .classViewMore is clicked, you can get the target of the event (most likely in the this pointer) that will be the .classViewMore item that was clicked on.
From that object, you can up to the parent (that gets you the Child item in your common parent.
From the Child, you can either go to a sibling to find Hidden Child or you can go up to the .classDiv parent and then find the containing .classHiddenDiv.
It's all about using the DOM hierarchy to find the other item that shares a common parent. Without actual HTML, it's a little hard to give exact code, but it would be something like this:
function classViewMoreClickHandler(e) {
// find next sibling of our parent
var childElem = this.parentNode;
var hiddenChildElem = childElem.nextSibling;
}
or, going up to the .classDiv parent, it would look like this:
function classViewMoreClickHandler(e) {
var parent = this.parentNode.parentNode;
var hiddenChild = parent.querySelectorAll(".classHiddenDiv")[0];
}
If you're going to work in plain JS regularly, then you probably want an analog for jQuery's .closest() method in plain javascript which finds an ancestor that matches a specific selector which can be really, really useful for this up to some common parent kind of DOM hiearchy navigation. For example, you could make a bit more robust solution using this:
function hasClass(elem, cls) {
var str = " " + elem.className + " ";
var testCls = " " + cls + " ";
return(str.indexOf(testCls) != -1) ;
}
function closest(start, cls) {
while (start && start !== document.documentElement && !hasClass(start, cls)) {
start = start.parentNode;
}
return start;
}
function classViewMoreClickHandler(e) {
var p = closest(this, ".classDiv");
if (p) {
var hiddenChild = p.querySelectorAll(".classHiddenDiv")[0];
// do whatever you want to hiddenChild here
}
}

Javascript not updating text within a div

I must be daft, but the javascript is not changing the containing div text as I would expect once the div is clicked:
favourite.onclick = function() {
loadXMLDoc('indexFavourite');
var linkclass = favourite.className;
if(linkclass == 'favouriteOption')
favourite.className = 'favouriteOptionActive',
favourite.className.update("New text");
else
favourite.className = 'favouriteOption';
}
Your syntax is way off, missing bracket and whatnot
favourite.onclick = function() {
loadXMLDoc('indexFavourite');
var linkclass = favourite.className;
if(linkclass == 'favouriteOption') {
favourite.className = 'favouriteOptionActive',
favourite.innerHTML="New text";
}
else {
favourite.className = 'favouriteOption';
}
}
What you are doing here is changing the class of a div (probably). And even this is kinda wrong. I mean
favourite.className = 'favouriteOptionActive',
favourite.className.update("New text");
should actually produce an error, because the string favouriteOptionActive doesn't have a method update. It could have only if you patch the String.prototype.
If you want to change the div's text you should use div.innerHTML or div.innerText.
favorite.text('New text') will set the text
note this will work if using jQuery, my bad!

Search in page with JavaScript Bootstrap

i would build a page with Bootstrap and i would use the navbar-search form for find the searched text in the same page.
What JS script i should use for do this?
I would that for every found text in the page the script add class "lead" to the p tag like this
<p class="lead">...</p>
How i can do this?
Thanks.
As Bootstrap requires jQuery for its plugins to work, I'll use it for your solution:
If your navbar-search is a class:
$(".navbar-search").on("keyup", function () {
var v = $(this).val();
$(".lead").removeClass("lead");
$("p").each(function () {
if (v != "" && $(this).text().search(v) != -1) {
$(this).addClass("lead");
}
});
});
Bear in mind that this will not look for words but for characters (so when you start typing say a, it will select both paragraphs straight away since both of them contain 'a'). If you want to search for words, you need to amend your code accordingly.
This solution is case-sensitive.
JSFiddle
So if you want to search for whole words, do this:
$(".navbar-search").on("keyup", function () {
var v = $(this).val();
$(".lead").removeClass("lead");
var re = new RegExp("\\b" + v + "\\b","g")
$("p").each(function () {
if (v != "" && $(this).text().search(re) != -1) {
$(this).addClass("lead");
}
});
});
Just bear in mind that you might want to escape your v before inserting it into the regexp if you expect people to search for something silly.
JSFiddle

How can I make greasemonkey search only within a table

Below is my code and currently it searches the whole webpage. I'm trying to figure out how to make it search only within a table. (There is only one table on the page).
Any help would be appreciated.
var TargetLink = $("a:contains('gg')");
var TargetSink = $("a:contains('u')");
if (TargetLink && TargetLink.length)
{
window.location.href = TargetLink[0].href;
}
else if (TargetSink && TargetSink.length)
{
window.location.href = TargetSink[0].href;
}
var TargetLink = $("table a:contains('gg')");
var TargetSink = $("table a:contains('u')");
EDIT:
You say there is only one table on the page. Do you absolutely know there will only ever be one table? Even if you think the answer is yes, I would try and add an id or class selector so that things won't break in the future.
Also, the following code can be simplified:
if (TargetLink && TargetLink.length)
to:
if (TargetLink.length)
Re: "could I combine those 2 variables into 1":
Use a comma in the selector, like so:
//--- Need more of the HTML structure for a better selector.
var TargetLink = $("table")
.find ("a:contains('gg'), a:contains('u')")
;
if (TargetLink.length) {
window.location.href = TargetLink[0].href;
}
If both kind of links are found, 'gg' will be used (first).

Categories