How to Add Class to Child Element of Parent using Javascript - javascript

I'm attempting to add a class to a p tag using the parent tag. Unfortunately, it does not appear to be adding the class .answer to the p tag. This is the code I have so far:
HTML
<div class="x-acc-content">
<p>This is sample text.</p>
</div>
Javascript
function($) {
$(this).children('div.x-acc-content').getElementsByTagName('p') [0].addClass('answer');
};

You can use .children('p') to get all children inside your div and then use .addClass() to add class to p tags .
Demo Code :
$(".x-acc-content").children("p").addClass("answer")
//or
//$(".x-acc-content").find("p").addClass("answer")
//or only first p tag
//$(".x-acc-content").find("p:first").addClass("answer")
.answer {
color: red
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="x-acc-content">
<p>This is sample text.</p>
<p>This is sample text.</p>
</div>

Try
$(".x-acc-content").find("p").addClass("answer");
or
$(".x-acc-content"). children("p").addClass("answer");
or
$(".x-acc-content p").addClass("answer");

Related

To add css property for particular tag of Div if class is foundJQuery

<div class="b">
<h1>Hello</h1>
<div class="a">
<p class="ABC">A..........Z</p> //this could be present in some pages
</div>
</div>
This is a piece of code in which I want to add css properties to <h1> of div with class "b" if <p> contains class="ABC".
How to do it?
if($('p').hasClass('ABC')){
$('h1').addClass('b');
}
You can use dot in between the tag name and class to refer the element.
Try $('div.b p.ABC') as the selector:
div.b will select any div with class b
The following space indicate the next matched element (p.ABC) will be inside the previous element (div.b).
p.ABC will select any div with class ABC
$('div.b p.ABC').addClass('test');
.test{
color: red;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="b">
<h1>Hello</h1>
<div class="a">
<p class="ABC">A..........Z</p> //this could be present in some pages
</div>
</div>
$('.b').each(function() {
var b = $(this);
var h1 = b.find('h1');
var p = b.find('div.a p');
if (p.is('[class="ABC"]')) {
h1.css({color: 'red'});
}
});
this check exact attribute class="ABC" if you want case insensitive you can use p.is('.abc') or p.hasClass('abc') and if you want if it have class ABC uppercase you can use is('[class^="ABC "],[class$=" ABC"], [class="ABC"]')
You can use:
if($(".b p.ABC").length)
To check if the element with the class b has a p tag as a child that has the class ABC.
You can then add css using .css to the appropriate element (here that element is $(".b h1")).
See working example below:
if($(".b p.ABC").length) {
$(".b h1").css({'color': 'red'});
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="b">
<h1>Hello</h1>
<div class="a">
<p class="ABC">A..........Z</p> //this could be present in some pages
</div>
</div>

Add a class when clicked on element, remove it when clicked elsewhere

I need to add a class(.highlight) to an element when its clicked upon, and it should be removed when clicked either on the element or anywhere else in the document.
I have managed to add and remove the class when the element is clicked using the classList.toggle() method but have no idea how to remove the class when a click happens in the document.
Here's my HTML, CSS and JS.
<p class="normal" onclick="detectClick(this)">This is paragraph 1</p>
<p class="normal" onclick="detectClick(this)">This is paragraph 2</p>
<p class="normal" onclick="detectClick(this)">This is paragraph 3</p>
.highlight {
background-color: yellow;
}
function detectClick(element) {
element.classList.toggle("highlight");
}
And here's where you can see the code in action, http://codepen.io/vbcda/pen/GodZmr
It can happen if you first remove exiting class 'highlight' from the element by using mousedown event by clicking anywhere in the body.
<body onmousedown="outerClick(this)"> // Add this in your html file
function detectClick(element) {
element.classList.toggle("highlight");
}
function outerClick(el){
var elements = document.querySelectorAll(".highlight");
for (var i = 0; i < elements.length; i++) {
elements[i].classList.remove('highlight');
}
}
I'd do something like this.
function detectClick(element) {
var elements = document.getElementsByClassName("normal");
Array.from(elements).forEach(function(element) {
element.setAttribute("class", "normal");
});
element.setAttribute("class", "normal highlight");
}
You could be explicit and use document.getElementsByClassName("normal highlight") too.
A simple lightweight solution
This can be done with just a couple of lines of CSS. The trick in this case is that you must add the tabindex attribute to each P so that it can receive focus.
Run the snippet below and click on the text to try.
p:not(:focus) { background-color: lightgray;}
p:focus { background-color: yellow;}
<p tabindex=1>This is paragraph 1</p>
<p tabindex=2>This is paragraph 2</p>
<p tabindex=3>This is paragraph 3</p>
if you want to use jquery:
$('.normal').click(function(e){
e.stopPropagation();
$(this).toggleClass('highlight');
});
$(document).click(function(){
$('.normal').removeClass('highlight');
});

How to remove the content from a "div" element using a button "onclick" function?

I have a div element that contains a number of images. When the user clicks a button, I want the contents of the div to be removed (not the div itself, I want to reuse the div to potentially add new content).
In my HTML, the div and button are defined as:
<body>
...
<div class="MyDiv"></div>
...
<button id="removeDiv" onclick="removeDivFunction()">remove Div Function</button>
...
</body>
How do I write a function that removes all elements from this div?
You have to call removeChild:
function removeDivFunction() {
MyDiv.parentNode.removeChild(MyDiv);
}
<div id="div1" style="height:100px;width:300px;border:1px solid black;background-color:yellow;">
This is some text in the div.
<p>This is a paragraph in the div.</p>
<p>This is another paragraph in the div.</p>
</div>
<br>
<button>Remove div element</button>
$(document).ready(function(){
$("button").click(function(){
$("#div1").remove();
});
});
David has already pointed you to an existing question/solution.
For reference consider reading: http://www.w3schools.com/js/js_htmldom_nodes.asp
Its always a good idea to assign id to the div.
Also if you are using jQuery you can delete element by $("#divid").remove() for reference see: https://api.jquery.com/remove/
I hope this helps.
function removeDivFunction() {
$(".MyDiv").remove();
}
<div class="MyDiv">I need to remove</div>
<button id="removeDiv" onclick="removeDivFunction()">remove Div Function</button>
function removeDivFunction() {
var element = document.getElementsByClassName("MyDiv")[0];
element.parentNode.removeChild(element);
}
DEMO
You can try
Html
<div id="some">Example</div>
<button onclick="myFunction()">Click me</button>
javascript
function myFunction() {
var child = document.getElementById("some");
child.parentNode.removeChild(child);
}
And if you want to erase content of DIV then use
child.innerHTML = "";

search and replace text inside html of div in javascript but not text inside tag

I've some HTML structure and i want to search particular text inside that HTML structure.
see below example
<h1>Try to span some text on this page</h1>
<div>
span is a <span>paragraph</span>.</div>
<p class="span ddd">This 123is a paragraph.1</p>
<div class="span ddd">This is some span in a div element.</div>
Now if I'm searching for "span" text then, "span" word should be wrapped with div tag.
But only "span" word in text and not from class or other tags.
i want output like this (wrap using div or span)
<h1>Try to <span class="search">span</span> some text on this page</h1> <div> <span class="search">span</span> is a <span>paragraph</span>.</div> <p class="span ddd">This 123is a paragraph.1</p> <div class="span ddd">This is some <span class="search">span</span> in a div element.</div>
<div id="wrapper">
<h1>Try to span some text on this page</h1>
<div>
span is a <span>paragraph</span>.
</div>
<p class="span ddd">This 123is a paragraph.1</p>
<div class="span ddd">This is some span in a div element.</div>
</div>
I have modifed your html by enclosing with a wrapper for getting my selector. But you can use your own selectors.
$(document).ready(function(){
var str=$('#wrapper').html();
$('#wrapper').html(str.replace( new RegExp(" span ","g"),"<div>span</div>"));
});
This code will do what you need.
Here is the jsffiddle for this.
If your problem is fixed then please don't forget to mark this as solved. Thanks.
I am not very sure if this is what you want. But something like this should work
$(function() {
var found = $('div:contains("span")');
});
Here is a fiddle
http://jsfiddle.net/z7ckK/
If you use *:contains it search it inside HTML.
UPDATE:
Initially missed the replace part. I have a solution, but for that you need a wrapping element over the search elements. Please check my fiddle. You will understand.
http://jsfiddle.net/z7ckK/3/
You can try this regex: (?<!<[^>])${searchWord}(?<![^>]<)
let innerHTML = document.body.innerHTML
let searchWord = 'span'
let regex = new RegEx(`(?<!<[^>])${searchWord}(?<![^>]<)`,gi)
innerHTML.replace(regex, (x)=> {
return `<div>x</div>`;
});

How to append text after last css class

I have the following html
<div class="someClass">
Some text
</div>
<div class="someClass">
Some other text
</div>
<div class="add>
<img src="someImage.jpg">
</div>
Now I'd like to append another div after a click on the add image - but only after the last div with the class "someClass".
If I use the following jQuery it will be appended after each someClass element, so multiple times.
$(".add img").live("click", function() {
$(".containerFooter").after("<div class='someClass'>test</div>");
});
Is there a way to only append it after the last div with the someClass attribute?
You are looking for the :last selector:
$(".someClass:last").after("<div class='someClass'>test</div>");
$('.someClass').last()
OR
$('.someClass:last')
will give you last element of class someclass
Use:
$(".someClass").last().append("<div class='someClass'>test</div>");
$(".add img").live("click", function() {
$(".someClass:last").after("<div class='someClass'>test</div>");
});
Sorry, dint read the question completely in first attempt, updated the ans!
Also your html has a typo , its make it
working demo
$(".someClass").last() //-> selects your last div with id = someClass
.after("<div class='someClass'>test</div>");//-> place the html after the selected div
Actual code below
$(".add").live("click", function(){
$(".someClass").last().after("<div class='someClass'>test</div>");
});
​
​
There may be an easier way, but a jquery class returns an array of applicable objects. So you can find the last such object, create a new jquery object from it, and then operate on that.
<html><title>JQuery Play</title>
<h1>JQuery Play</h1>
<script src="jquery-1.4.1.js" type="text/javascript" ></script>
<script type="text/javascript">
function add()
{
var x=$(".someClass");
$(x[x.length-1]).after("Added text");
}
</script>
<div class="someClass">
Some text
</div>
<div class="someClass">
Some other text
</div>
<div class="add">
<button onclick="add()">Add</button>
</div>
</html>

Categories

Resources