Choose elements that are not contained within a certain designated element

I am looking to choose one or more elements that are NOT children of a specific element.

<html>
<body>
    <div>
        <p>
            <b>
                <i> don't pick me </i>
            </b>
        </p>
    </div>  
    <div> 
        <i>don't pick me either </i>
    </div>  
    <i> select me </i>
    <b> 
        <i> select me as well </i>
    </b>
</body>
</html>

In the illustration above, my goal is to pick all 'i' elements that are not contained within div elements. It's not straightforward using ('div i') in :not() function.

How can I pick all i elements outside of div elements? The common suggestion is to use jQuery, such as:

nondiv_i = all_i.not(all_div.find("i")) 

I cannot utilize jQuery, but jqLite - which does not have a not()-function. A jqLite solution is appreciated too! Is there a way to achieve this without repetitive iterations and comparisons?

Edit: To clarify, I want no div ancestors for my i-elements, not just direct div parents.

A related XPath would be like this:

//i[not(ancestor::div)]

Answer №1

function checkChild(parentNode, childNode) {
    var elements = parentNode.getElementsByTagName(childNode.tagName);
    for (var index = -1, length = elements.length; ++index < length;) {
        if(elements[index]==childNode){
            return true;
        }
    }
    return false;
}

in the context of your specific situation;

isTags = document.getElementsByTagName("i");
divTags = document.getElementsByTagName("div");
nodesWithoutDivParent = [];
var found;
for(i=0;i<isTags.length;i++){
    found = false;
    for(j=0;j<divTags.length;j++){
        if(checkChild(divTags[j], isTags[i])){
            found = true;
            j = divTags.length;
        }

    }
    if(!found){
        nodesWithoutDivParent.push(isTags[i]);
    }

}

Answer №2

To target all <i> tags, add a custom class like "itag". Afterwards, you can retrieve them using getElementsByClassName:

var elements = document.getElementsByClassName("itag");
console.log("Total number of elements: " + elements.length);

You can then access them by their index:

console.log(elements[0]);
console.log(elements[1].innerHTML); // Retrieve text inside the i tag

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

AngularJS fetching data with two separate AJAX requests for both HTML and JSON responses

After activating network capture in my web browser to inspect the ajax calls coming out of AngularJS, I noticed that each call seems to result in two outcomes: URL|Protocol|Method|Result|Type|Received|Taken /p/jobs/03512dc8-6f25-49ea-bdff-0028ac2023cb|HTT ...

Exploring the contrast between web elements and ElementFinders in Protractor

After diving into the Protractor API documentation and watching a video on Youtube, I'm still unsure. Is ElementFinder a shortcut or pointer to webElement, and is Element an instance of a certain class that represents webpage elements? ...

What is the best method for sending a DbGeography parameter to MVC?

I am working on developing an API that allows users to save polygons on the server using ASP.NET MVC 5. Can anyone guide me on how to properly format the AJAX parameters for posting requests with DbGeography? This is what I have tried so far: $.ajax({ ...

sticky navigation causing issues with tab functionality

Currently in the process of developing a website with a rather intricate sticky navigation bar. The JavaScript code being utilized to achieve this functionality is as follows: // Code for creating a sticky navigation bar document.addEventListener("s ...

Create a WebGL object remotely on the server

Exploring potential project ideas, I was curious to see if it's feasible to produce a WebGL scene or object on the server side and then have it rendered on the client. The motivation behind this is that generating a scene typically involves utilizing ...

Complete the modal window form

I'm currently facing an issue with populating a modal window form. To provide some context, when I click on a grid row to edit a user, I make an ajax call which fetches specific data related to that user. Here is the existing code snippet: <modal ...

Ensuring Map Safety in Typescript

Imagine having a Map structure like the one found in file CategoryMap.ts export default new Map<number, SubCategory[]>([ [11, [100, 101]], [12, [102, 103]], ... ]) Is there a way to create a type guard for this Map? import categoryMap fro ...

`Custom transitions between sections using fullpage.js`

Has anyone used the fullpage.js extension to achieve an animation similar to this one, where sections are destroyed on scroll? ...

Having trouble understanding why getStaticProps function is not loading before the main exported function

When I use npm run dev to troubleshoot this issue, it utilizes getStaticProps to process various d3 properties before injecting them into the main output function during runtime. However, it seems that getStaticProps is not running as expected - a consol ...

Methods for setting the value of a scope variable within a controller's function

I have a goal of presenting a page that calculates a balance in the background and displays it. To achieve this, I decided to separate the balance into its own directive. Here is the directive I have created: app.directive('smBalanceInfo', fun ...

Concatenate a variable string with the JSON object key

I am currently working on a request with a JSON Object structure similar to the following: let formData = { name: classifierName, fire_positive_examples: { value: decodedPositiveExample, options: { filename: 'posit ...

Behind the scenes, unable to launch due to Schema Error

My experience with Backstage was going smoothly until I ran into an issue after executing a yarn install this afternoon. Now, whenever I attempt to run yarn dev, it fails with the following error: [0] Loaded config from app-config.yaml [0] <i> [webpa ...

My div does not refresh when using .load

I implemented ajax to retrieve the start time and end time from another page, and used setInterval to call this function every second like so. setInterval(function () { CheckTime() }, 1000); function CheckTime() { $.ajax({ url: "Get_TIme. ...

Utilizing various Firestore requests at varying intervals using the useEffect hook in React

useEffect(async() => { await getWord(); const interval = setInterval(() =>{ time2 = time2 - 1; if (time2 == 0) { clearInterval(interval); let dataURL = canvasRef.current.toDataURL(); const db = firebase.firestore(); ...

Error message: The AJAX POST request using jQuery did not return the expected data, as the data variable could not be

There is a script in place that retrieves the input text field from a div container named protectivepanel. An ajax post call is made to check this text field in the backend. If the correct password is entered, another div container panel is revealed. < ...

Using JQuery's $.post function can be unreliable at times

Looking for help with a function that's giving me trouble: function Login() { var username = document.getElementById('username').value; var password = document.getElementById('password').value; $.post("Login.php", { ...

When a text is wrapped by an HTML div using absolute positioning, is there a way to prevent it from wrapping without relying on white space

I have a group of div elements positioned absolutely on the screen. If any div contains content that is too big for the screen, the browser wraps it into multiple lines to fit. However, I do not want this behavior. Instead, I want the overflowing content ...

Manipulate sibling elements using jQuery's addClass and remove methods

I have implemented a function that adds the class active to elements when they reach the top of the browser, ensuring that the next element will scroll in over the top. While this works smoothly in Chrome, I am encountering some jumping behavior when testi ...

I was surprised to find something other than a gulp folder in the node_modules directory after running npm install gulp --save-dev

Seeking some guidance on my process - can someone point out if I am making a mistake? Downloaded Node from their official website Global installation of Gulp (npm install --global gulp) Created a folder and initiated it by running (npm init), which gene ...

AngularJS Data Binding Issue - Watch cycle fails to trigger

View the JSFiddle example here: https://jsfiddle.net/pmgq00fm/1/ I am trying to achieve real-time updating of my NVD3 chart by utilizing the setInterval() function on line 39, which updates the data bound to the directive. Here is a brief overview of the ...