Super Useful Tool to target Any object on the screen.

Feb 08, 2024

So, I have been dealing with trying to implement js on various objects on the screen and have seen a ton of creative solutions on here. I found a really simple way to target any object that is visible on the screen and wanted to share it. 

This method gets all divs with the data-model-id and creates a <p> set to that div's data-model-id and places it directly under the object. So far, it works on any visual element I've added to the screen. I'm including a sample project below that I've gutted that I used as an internal example. It has the code set to a button that we can drop on a slide, preview the slide and run, then delete once we have the item name we need.

 

The code: 

// Get all div elements with the data-model-id attribute
var divsWithDataModelId = document.querySelectorAll('div[data-model-id]');

// Loop through each div
divsWithDataModelId.forEach(function(div) {
    // Get the value of the data-model-id attribute
    var modelId = div.getAttribute('data-model-id');
    
    // Create a new <p> element
    var paragraph = document.createElement('p');
    
    // Set the text of the <p> element to the value of data-model-id
    paragraph.textContent = modelId;
    
    // Append the <p> element to the current div
    div.appendChild(paragraph);
});

 

 

1 Reply